Thread: knapsack

  1. #1
    Registered User
    Join Date
    Aug 2012
    Posts
    32

    knapsack

    Hi guys,
    i'm reading a few examples about recurtion in the internet and came across this example: The 0-1 Knapsack Problem In C | DZone
    two things:
    1. is this a recursive code ?
    2. how can i write it in a more general way.. say i have N items and N<=30, and the value is V and weight is Wi and maximum wegight is W?
    in this case i still need the difine ?

    thanks.

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    There are certainly better examples of the knapsack problem, with better variable names, better indentation, better code organization, better scalability, etc. Also, if you examine the algorithm, or read the comments, you will find out that it does not provide a solution to the 0-1 knapsack problem. It is unbounded, letting you reuse items.

    1. Does the fill_sack function ever call itself? No. Thus that is not recursive code. It is common to see a recursive solution to the knapsack problem though.
    2. Google for other examples and see what they do. You need to change n, c and v in the example you provided, to reflect the right number of items, the right costs and right values. You can do that by adding a loop to ask the user for input of how many items, and what each one is.

    Here, for instance, is a better example of the 0-1 knapsack: Knapsack problem/0-1 - Rosetta Code. Can you figure out if that one is recursive?

  3. #3
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    I guess you are learning recursion about know.Knapsack problem is a very good example for algorithms and complexity,so i would suggest you to try learning recursion and after gaining experience return to the problem and face it (both the discrete and the non-discrete versions because greedy strategy gives the optimum solution to the non-discrete one,but not in the other etc..shall not tell more now in order not to complex you )

    1-Is this a recursive code?
    Oh anduril already answered

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Knapsack problem
    By viblic in forum C Programming
    Replies: 8
    Last Post: 12-04-2011, 02:58 PM
  2. Knapsack
    By anirban in forum C++ Programming
    Replies: 4
    Last Post: 08-21-2007, 01:26 AM
  3. knapsack problem
    By fnfn in forum C++ Programming
    Replies: 1
    Last Post: 07-19-2007, 03:14 PM
  4. Help with my Knapsack Code
    By ghop2003 in forum C++ Programming
    Replies: 4
    Last Post: 11-24-2006, 03:08 PM
  5. Knapsack Problem
    By Fork in forum C Programming
    Replies: 4
    Last Post: 11-13-2006, 12:42 PM