Question: I am solving the knapsack problem using recusrison. All numbers provided by user are on one line. first number is target weight followed by the

I am solving the knapsack problem using recusrison. All numbers provided by user are on one line. first number is target weight followed by the nubers that need to be inserted into an array(ie, 20 15 10 10 5 4). My program works perfectly right now when I know the amount of array elements the user will enter after the target weight (right now set to 5). Problem is I will not know how many numbers will need to go into array. I am using an array list for the recursion. How do I use an array list for the input and tranfer to recusion??

import java.util.*; import java.io.*;

public class Program4{

public static int arrayItems[]; public static ArrayList values = new ArrayList(); public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.println("Please enter the items:"); int target = input.nextInt(); arrayItems = new int[5]; for(int i=0;i<5; i++){ arrayItems[i]= input.nextInt();} System.out.println(" Target Weight: "+target);

knapsack(target, 0); }

public static void knapsack(int target, int i){

if (i == (arrayItems.length)){ //base condition to stop the recursion

//If the target weight is 0 then displays the values if (target == 0){ System.out.println("The solution of recursive knapsack problem is by filling with weights: "); for (int j = 0; j < values.size(); j++){ System.out.print(values.get(j) + "\t");}

System.out.println();}

return;}

//if the i'th element is exist then the move the weights(arrayItems)

//into values

values.add(arrayItems[i]);

knapsack(target - arrayItems[i], i + 1);

values.remove(values.size() - 1);

knapsack(target, i + 1);

}}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!