in reply to Re: Gift Exchange Code
in thread Gift Exchange Code

Maybe I misunderstand the term ‘bin packing’, but I always thought that it applied to the problem of assigning weighted objects to bins with a maximum weight allowance, in such a way that there is as little “wasted space” as possible. Aside from the general terminology of putting things in a bin, this idea doesn't seem to share anything with that problem setting. (The pseudo-code looks good for the OP's problem, though, assuming that remove is non-destructive.)

Replies are listed 'Best First'.
Re^3: Gift Exchange Code
by MidLifeXis (Monsignor) on Oct 30, 2008 at 17:23 UTC

    You are correct. I tend to over-generalize problems. Perhaps a more proper comparison (at least from the standpoint of the algorithm) would be a knights tour problem, tic-tac-toe, or some other game-type problem.

    The difference between bin-packing and this problem, is that I can assume that every item in the data set must be used. In bin packing that may not be true (bin.size < data.sum(size)).

    The solutions, however, can be very similar. One area of difference that I can see is that the selection of the first item ($x = people.pop) is not correct. Perhaps removing it completely and modifying the termination check (the if clause at the top) to some fitness test (less than N% wasted space, for example) would get close enough to be a solution. Note that I did not say the best solution.

    Basically I am doing a depth first search of all option paths, pruning the tree (FAILURE) if an invalid combination occurs, and building the answer as I unwind the call stack (results.push) if I exhaust the list of people (people.empty).

    Now, this solution (and I don't think the original problem asked to do this) does not handle the case where there are an odd number of people in the list, and it pairs up people rather than allowing A to give to B, B to give to C, and C to give to A. Perhaps CountZero's solution would be better in this case.

    --MidLifeXis