Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating all permutations of N balls in M bins

Tags:

r

permutation

I want to generate a set of permutations of n balls in m bins. The following set of nested lists generates those permutations.

n <- 3
m <- 4
v <- rep(0,m)
for (i in n:0){
  for (j in (n-sum(i)):0){
    for (k in (n-sum(i,j)):0){
      for (l in (n - sum(i,j,k)):0){
        v <- c(i,j,k,l)
        print(v)
        if (sum(v) == n){ break }
      }
    }
  }
}

Which prints the solution:

[1] 3 0 0 0
[1] 2 1 0 0
[1] 2 0 1 0
[1] 2 0 0 1
[1] 1 2 0 0
[1] 1 1 1 0
[1] 1 1 0 1
[1] 1 0 2 0
[1] 1 0 1 1
[1] 1 0 0 2
[1] 0 3 0 0
[1] 0 2 1 0
[1] 0 2 0 1
[1] 0 1 2 0
[1] 0 1 1 1
[1] 0 1 0 2
[1] 0 0 3 0
[1] 0 0 2 1
[1] 0 0 1 2
[1] 0 0 0 3

The total number of permutations will be choose(n+m-1,m-1), and the order of the permutations does not matter to me. But I am having a hard time making this into a function that can take an arbitrary number of bins. (I won't spoil the well with my attempts, it is just jumble of nested loops though.) So if someone more saavy than me could translate the nested loops above into a function I would appreciate it.

Or if there is already a function available to conduct this type of permutation (or a different algorithm to follow) I would appreciate being told about it. I would prefer an approach that does not generate superfluous permutations (here ones that do not add up to n) and then discards them, but for small problems like this a solution that does that would be acceptable.

like image 596
Andy W Avatar asked Nov 21 '14 15:11

Andy W


People also ask

How many ways can you put N balls in M buckets?

There are only six ways.

How many ways can n balls be placed in k boxes?

How many ways we can distribute n distinguishable balls into k distinct bins and ordering does not matter? There are n distinguishable balls and we can put k-1 bars in between the n balls . So totalno of permutations of n balls and k-1 bar is (n+k-1)!/(k-1)!.

How many ways are there of putting nm indistinguishable balls into M distinguishable bins so that each bin has at least one ball?

So the total number of ways of distributing N indistinguishable balls into M bins such that exactly one bin has exactly n balls in it is 2(N−n+M−2N−n)+(M−2)(N−n+M−3N−n).


1 Answers

library(partitions)
compositions(3,4)

# [1,] 3 2 1 0 2 1 0 1 0 0 2 1 0 1 0 0 1 0 0 0
# [2,] 0 1 2 3 0 1 2 0 1 0 0 1 2 0 1 0 0 1 0 0
# [3,] 0 0 0 0 1 1 1 2 2 3 0 0 0 1 1 2 0 0 1 0
# [4,] 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 2 2 2 3
like image 195
Josh O'Brien Avatar answered Sep 19 '22 12:09

Josh O'Brien