所有将k个组拆分为k个组的方法-R [英] All possible ways to split n over k groups - R
问题描述
我陷入了数学难题.我想制作一个函数,以所有方式将整数"n"划分为"k"个组,这样每个组中的"k"至少为1(k> = 1).
I am stuck in a mathematical problem. I would like to make a function that outputs all the ways an integer "n" can be divide into "k" groups in such a way that in each group "k" is at least 1 (k >= 1).
该函数可能类似于:
n_ways <- function(n,k) {...}
我想要一个dataFrame作为输出.因此适用于: n_ways(5,3)
I would like a dataFrame as an output. So for: n_ways(5,3)
A B C
1 3 1 1
2 1 3 1
3 1 1 3
4 2 2 1
5 2 1 2
6 1 2 2
dataFrame中解决方案的显示顺序并不重要.
The order in which the solutions are presented in the dataFrame is not important.
我正在寻找类似此处和
I looked for solutions like here and in other languages like here and here. Unfortunately I am not that good to make a function that suits my problem based on this, but hopefully you are.
非常感谢!
推荐答案
您可以使用partitions
软件包:
library(partitions)
t(compositions(5,3,FALSE))
#[1,] 3 1 1
#[2,] 2 2 1
#[3,] 1 3 1
#[4,] 2 1 2
#[5,] 1 2 2
#[6,] 1 1 3
从相应的帮助文件中
函数composition()返回所有2 ^(n-1)种对整数进行分区的方式;因此4 + 1 + 1不同于1 + 4 + 1或1 + 1 + 4.
Function compositions() returns all 2^(n-1) ways of partitioning an integer; thus 4+1+1 is distinct from 1+4+1 or 1+1+4.
这篇关于所有将k个组拆分为k个组的方法-R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!