Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Systems An Application Oriented Approach Complete Version

Authors: Michael Kifer, Arthur Bernstein, Richard Lewis

2nd Edition

0321268458, 978-0321268457

More Books

Students also viewed these Databases questions

Question

1. Identify six different types of history.

Answered: 1 week ago

Question

2. Define the grand narrative.

Answered: 1 week ago

Question

4. Describe the role of narratives in constructing history.

Answered: 1 week ago