Ask Question
24 December, 10:11

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.

+4
Answers (1)
  1. 24 December, 11:18
    0
    see explaination

    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)

    W = = 0)

    return 0;

    if (wt[n-1] > W)

    return calculate (W, wt, val, n-1);

    else return max (val[n-1] + calculate (W-wt[n-1], wt, val, n-1),

    calculate (W, wt, val, n-1)

    );

    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
    {

    profits[i]=sc. nextInt ();

    }

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

    for (int j=0; j
    {

    weight[j]=sc. nextInt ();

    }

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

    }

    Note: change the at with the sign

    }
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Use greedy approach to implement fractional knapsack problem. a. Ask user for knapsack capacity. b. Ask user for n objects weights and ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers