Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re^2: knapsack problem solved by regex

by rubasov (Friar)
on Mar 14, 2010 at 17:37 UTC ( #828593=note: print w/ replies, xml ) Need Help??


in reply to Re: knapsack problem solved by regex
in thread knapsack problem solved by regex

I've just skimmed your code, but if I'm right then your algorithm is lucky to find the correct output for this particular input, but does not give the correct answer in general.

You're filling the knapsack with the items in the order of their relative value (v/w), so consider the following case when your knapsack is almost full (let's suppose there's still room for w=4):

nr w v v/w 1x 3 3.1 31/30 # case a 2x 2 2 1 # case b

Your algorithm will choose case 'a', increasing the full value by 3.1, however the correct choice is to choose case 'b' increasing the full value by 4. That's why you have to backtrack.


Comment on Re^2: knapsack problem solved by regex
Download Code
Re^3: knapsack problem solved by regex
by BrowserUk (Pope) on Mar 14, 2010 at 18:05 UTC

    Cool. I knew (guessed) it was too easy, but it worked for several test sets. Thanks for the explanation.

    Actually, scrap the above, because according to the wikipedia page,

    The most common formulation of the problem is the 0-1 knapsack problem, which restricts the number xj of copies of each kind of item to zero or one.

    So you can't have 2 of one item?


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Think of the following: a solution to the 0-1 knapsack problem can be easily generalized to the bounded case, you just have to explicitly list the items with nr>1. Think of my previous example as this (just written abbreviated there):
      w v v/w 3 3.1 31/30 # case a 2 2 1 # case b (together with the following line) 2 2 1 # case b

        I see. Two different items with the same values and weights. Gotcha.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://828593]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2014-10-23 10:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (125 votes), past polls