Enhance documentation in FractionalKnapsack (#5795)

This commit is contained in:
Hardik Pawar
2024-10-16 16:59:15 +05:30
committed by GitHub
parent dfff8d95d2
commit 169a01e0c8

View File

@ -3,39 +3,50 @@ package com.thealgorithms.greedyalgorithms;
import java.util.Arrays;
import java.util.Comparator;
// Problem Link: https://en.wikipedia.org/wiki/Continuous_knapsack_problem
/**
* The FractionalKnapsack class provides a method to solve the fractional knapsack problem
* using a greedy algorithm approach. It allows for selecting fractions of items to maximize
* the total value in a knapsack with a given weight capacity.
*
* The problem consists of a set of items, each with a weight and a value, and a knapsack
* that can carry a maximum weight. The goal is to maximize the value of items in the knapsack,
* allowing for the inclusion of fractions of items.
*
* Problem Link: https://en.wikipedia.org/wiki/Continuous_knapsack_problem
*/
public final class FractionalKnapsack {
private FractionalKnapsack() {
}
// Function to perform fractional knapsack
/**
* Computes the maximum value that can be accommodated in a knapsack of a given capacity.
*
* @param weight an array of integers representing the weights of the items
* @param value an array of integers representing the values of the items
* @param capacity an integer representing the maximum weight capacity of the knapsack
* @return the maximum value that can be obtained by including the items in the knapsack
*/
public static int fractionalKnapsack(int[] weight, int[] value, int capacity) {
// Create a 2D array to store item indices and their value-to-weight ratios.
double[][] ratio = new double[weight.length][2];
// Populate the ratio array with item indices and their value-to-weight ratios.
for (int i = 0; i < weight.length; i++) {
ratio[i][0] = i; // Assign item index.
ratio[i][1] = value[i] / (double) weight[i]; // Calculate and assign value-to-weight ratio.
ratio[i][0] = i;
ratio[i][1] = value[i] / (double) weight[i];
}
// Sort items by their value-to-weight ratios in descending order.
Arrays.sort(ratio, Comparator.comparingDouble(o -> o[1]));
int finalValue = 0; // Variable to store the final knapsack value.
double current = capacity; // Variable to track the remaining capacity of the knapsack.
int finalValue = 0;
double current = capacity;
// Iterate through the sorted items to select items for the knapsack.
for (int i = ratio.length - 1; i >= 0; i--) {
int index = (int) ratio[i][0]; // Get the item index.
int index = (int) ratio[i][0];
if (current >= weight[index]) {
// If the entire item can fit in the knapsack, add its value.
finalValue += value[index];
current -= weight[index];
} else {
// If only a fraction of the item can fit, add a proportionate value.
finalValue += (int) (ratio[i][1] * current);
break; // Stop adding items to the knapsack since it's full.
break;
}
}
return finalValue;