2
$\begingroup$

I have four letters: A B C D, I need to calculate all the combinations on the follow type:

A - B
A - C
A - D
A - BC
A - BD
A - CD
A - BCD

AB - C
AB - CD
AB - D

ABC - D

As you can see no letters are repeated LEFT - RIGHT, IF the letter is on the left it is not repeated on the right again. I need a method to generate all those possible combinations.

AND

the order of the combinations is not important, If I use ABC I don't need other combinations with CBA or BAC, as you cann see I wrote:

A - BC

and NOT

A - CB

indeed.

I Need all the combinations that 4 letters could generate without repeating the same letter on left and on the right.

Could someone help me?

$\endgroup$
2
  • $\begingroup$ Did you check over on stack overflow? stackoverflow.com/search?q=%5Br%5D+combinations , I suspect it may have been answered already (or very close to answered). $\endgroup$
    – Andy W
    Commented Nov 10, 2011 at 19:26
  • 1
    $\begingroup$ It's unclear what a "combination" is. (You do not use the word in its usual mathematical or statistical sense.) For instance, would AC-BD qualify? B-AC? BC-A? If you can't define this, then it would help to see several complete, correct examples. Also, for this question to have some relevance to the site, please explain its connections with statistics or machine learning. $\endgroup$
    – whuber
    Commented Nov 10, 2011 at 19:53

1 Answer 1

4
$\begingroup$
lt <- c("A","B","C","D")

# between 1 and 3 on the left
for (n.left in 1:3) {
  left.idxs <- combn(4, n.left)
  apply(left.idxs, 2, function(left.idx) {
    left <- lt[left.idx]
    available.right <- lt[-left.idx]
    for (n.right in 1:(4-n.left)) {
      right.idxs <- combn(length(available.right), n.right)
      apply(right.idxs, 2, function(right.idx) {
        right <- available.right[right.idx]
        cat(paste(paste(left, collapse=""), "-", paste(right, collapse=""), "\n"))
      })
    }
  })
}

I just made this print them out; you could store them otherwise (append to a list or some such). combn is used to get all the combinations, but this has to be looped over since you can have 1, 2, or 3 items on the left. For each combination, the remaining letters are made available for choosing for the right, and the same process is repeated, but the right can only have between 1 and 4-the number on the left.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.