gpt4 book ai didi

r - 将 n 拆分为 k 组的所有可能方法 - R

转载 作者:行者123 更新时间:2023-12-01 07:35:33 25 4
gpt4 key购买 nike

我被困在一个数学问题中。我想制作一个函数,该函数输出整数“n”可以分成“k”组的所有方式,使得每组中的“k”至少为1(k> = 1)。

该函数可能类似于:

n_ways <- function(n,k) {...}

我想要一个数据帧作为输出。所以对于: 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

解决方案在数据帧中出现的顺序并不重要。

我寻找解决方案,如 here 和其他语言,如 herehere 。不幸的是,我不太擅长基于此制作适合我的问题的功能,但希望您是。

非常感谢!

最佳答案

您可以使用 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

从各自的帮助文件

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.

关于r - 将 n 拆分为 k 组的所有可能方法 - R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39435018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com