216k views
4 votes
Use greedy approach to implement fractional knapsack problem. a. Ask user for knapsack capacity. b. Ask user for n objects weights and profits or read an input.txt that contains n objects weights and profits. c. List objects that maximize the profit and show the maximum profit as output considering knapsack capacity.

1 Answer

2 votes

Answer:

see explaination

Step-by-step explanation:

/*

* To change this license header, choose License Headers in Project Properties.

* To change this template file, choose Tools | Templates

* and open the template in the editor.

*/

package knapsack;

import java.util.*;

/**

*

* atauthor Administrator

*/

public class MyKnapsack {

static int max(int a, int b) { return (a > b)? a : b; }

static int calculate(int W, int wt[], int val[], int n)

if (n == 0

public static void main(String[] args)

{

Scanner sc=new Scanner(System.in);

System.out.printf("|Enter value of capacity");

int Capacity =sc.nextInt();

System.out.printf("|Enter value of number of objects");

int n=sc.nextInt();

int profits[] = new int[n];

int weight[] = new int[n];

System.out.printf("|Enter values for profits");

for(int i=0;i<n;i++)

{

profits[i]=sc.nextInt();

}

System.out.printf("|Enter values for weights");

for(int j=0;j<n;j++)

{

weight[j]=sc.nextInt();

}

System.out.println(calculate(Capacity,weight, profits, n));

}

Note: change the at with the sign

}

User Divinedragon
by
5.2k points