本文介绍了生成包含n个元素的所有k个置换并重复的矩阵的好算法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,假设我设置了S = {A1,A2},并且我想以3为一组计算这两个元素的所有可能排列.
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)
我正在使用R语言.我一直在尝试寻找某种算法来生成像这样的矩阵,但是到目前为止还没有成功.
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.
感谢您的帮助.
推荐答案
获得所有排列的一种方法是使用expand.grid
:
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
如@ Forest1所建议,您可能要排除第一行和最后一行,因为它们包含AAA
和BBB
.这可以通过
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]
这篇关于生成包含n个元素的所有k个置换并重复的矩阵的好算法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!