Search code examples
algorithmrandomset-theory

Generate one of many ways of distributing toys among children


  • There are N children and a finite set T of distinguishable toys;
  • Each child likes a particular subset Ti of all toys;
  • Each child needs to own an exact number ti <= |Ti| of toys, but only from the toys that child likes;
  • Some toys are liked by more than one child.
  • A toy can't be owned by multiple children
.

There are possibly many ways to satisfy each child's need for toys.

Problem: Given N, {Ti}, {ti} and a seeded RNG, from all possible configurations of toys owned by children I need to pick a uniformly distributed (or at least close to uniformly distributed) configuration, that is, a mapping from children to the toys they own.

Generating all the possible configurations and picking j-th is no go — there may be a lot of those.

In the example below there are 4 children: red, blue, green and yellow. Red needs to own 4 toys, blue — 5, green — 3, yellow — 3. Toys children like are inside the rectangles of corresponding colors.

Children craving for toys

So what I need is either an outline of an algorithm to generate a well-distributed Map<Child, Set<Toy>>, or any links that would be useful to read for solving the problem.


Solution

  • Prepare a bipartite graph as follows. For each child i, make t_i vertices. For each toy j, make one vertex. Whenever child i likes toy j, connect all of i's vertices to j's vertex. The valid assignments of toys to children correspond to perfect matchings in this graph. Compute one assignment using your favorite matching algorithm (e.g., Hopcroft--Karp) and then run the Markov chain of Jerrum and Sinclair as long as desired.