问题
So, let's say I have set S = {A1, A2} and I want to calculate all possible permutations of these two elements in groups of 3.
I would like to generate a matrix such as this:
(A1 A1 A2)
(A1 A2 A1)
(A2 A1 A1)
(A2 A2 A1)
(A2 A1 A2)
(A1 A2 A2)
I'm using R language. I've been trying to find some algorithm to generate a matrix like this, but haven't been successful so far.
Thanks for your help.
回答1:
One way to obtain all permutations would be to use expand.grid
:
a <- c("A", "B")
expand.grid(a, a, a)
# Var1 Var2 Var3
# 1 A A A
# 2 B A A
# 3 A B A
# 4 B B A
# 5 A A B
# 6 B A B
# 7 A B B
# 8 B B B
As suggested by @Forest1, you may want to exclude the first and the last row, since they contain AAA
and BBB
. This can be achieved by
expand.grid(a, a, a)[2:7]
来源:https://stackoverflow.com/questions/34031705/a-good-algorithm-to-generate-a-matrix-containing-all-k-permutations-of-n-element