A good algorithm to generate a matrix containing all k-permutations of n elements with repetition?

♀尐吖头ヾ 提交于 2019-12-24 12:07:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!