Home Forums SQL Server 2012 SQL 2012 - General Grouping and Sorting challenge RE: Grouping and Sorting challenge<!-- 864 --><!-- 864 -->

  • CELKO (8/20/2014)


    Google “bin packing” and “knapsack” problems. Ther is also a classic book availalbre as a PDF download. http://www.or.deis.unibo.it/knapsack.html. It has heavy math and awful FORTRAN.

    The bottom line is that you are screwed for the general case. This is an NP Complete problem.

    Also your specs need to be more precise as to how you determine the sizes; would 3 identical sized bags and 1 outlier be better than 4 near-matches? Etc.

    Since you have a limited problem of 4 knapsacks and 10 items. My best guess is first partition the 10 items into 2 subset of approximately equal weight. Whatever that means and assuming it is possible. Then partition each of those recursively and hand them out to the 4 drivers.

    This will require a table of 2^10 rows (1024) with all possible combinations of the weights and 0 in each column.

    CREATE TABLE Routes

    (partition_nbr INTEGER NOT NULL PRIMARY KEY,

    r01 INTEGER NOT NULL

    CHECK(r01 IN 0, 700),

    r02 INTEGER NOT NULL

    CHECK(r02 IN 0, 210)

    r10 INTEGER NOT NULL

    CHECK(r10 IN 0, 525));

    Load the routes (exercise for the student) then

    SELECT partition_nbr, (r01+r02+ ..+r10) AS wgt

    FROM Routes;

    Pick partitions closest to the mid point.

    Table with 2^10 rows? "Screwed in the general case"? I don't believe any of that is necessary. This is one of those places where a loop (please see the solution I posted above) actually does work quite well and it's self correcting based on the number of rows in the two tables. And, remember... I'm one of those that hates loops! 😉

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)