Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All possible ways to split n over k groups - R

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).

The function could look something like:

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

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

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.

Thanks a lot in advance!

like image 921
RobinvG Avatar asked Dec 07 '22 21:12

RobinvG


1 Answers

You can use the partitions package:

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

From the respective help file

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.

like image 124
cryo111 Avatar answered Dec 28 '22 22:12

cryo111