Using recursion Java data struct Write a program that solves

Using recursion (Java data struct.)

Write a program that solves the Knapsack problem. Code to the following standards.

Your source of items to put into the knapsack should consist of five randomly generated integers in the range of 1 to 20.

Your knapsack can hold 20 lbs.

Solution

Please find the below code I have written for you.

Code:

class Knapsack
{

static int max(int a, int b) { return (a > b)? a : b; }
  
static int knapSack(int W, int wt[], int val[], int n)
{
if (n == 0 || W == 0)
return 0;
if (wt[n-1] > W)
return knapSack(W, wt, val, n-1);

else return max( val[n-1] + knapSack(W-wt[n-1], wt, val, n-1),
knapSack(W, wt, val, n-1)
);
}

public static void main(String args[])
{
int val[] = new int[]{ input random numbers}; // Please modify it
int wt[] = new int[]{ input random numbers }; // Please modify it
int W = 50;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));
}
}

If you have any doubt please mention that in comments.

Happy Chegging !

Using recursion (Java data struct.) Write a program that solves the Knapsack problem. Code to the following standards. Your source of items to put into the knap

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site