Skip to content

algorithm: knapsack #69

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 25, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions dynamic_programing/Knapsack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* @function knapsack
* @description Given weights and values of n (numberOfItems) items, put these items in a knapsack of capacity totalWeight to get the maximum total value in the knapsack. In other words, given two integer arrays values[0..n-1] and weights[0..n-1] which represent values and weights associated with n items respectively. Also given an integer totalWeight which represents knapsack capacity, find out the maximum value subset of values[] such that sum of the weights of this subset is smaller than or equal to totalWeight. You cannot break an item, either pick the complete item or don’t pick it (0-1 property).
* @Complexity_Analysis
* Space complexity - O(1)
* Time complexity
*      Best case   -   O(numberOfItems * totalWeight)
*      Average case   -   O(numberOfItems * totalWeight)
*      Worst case   -   O(numberOfItems * totalWeight)
*
* @return maximum value subset of values[] such that sum of the weights of this subset is smaller than or equal to totalWeight.
* @see [Knapsack](https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/)
* @example knapsack(3, 8, [3, 4, 5], [30, 50, 60]) = 90
*/
export const knapsack = (
numberOfItems: number,
totalWeight: number,
weights: number[],
values: number[]
) => {
// Declaring a data structure to store calculated states/values
var dp: number[][] = new Array(numberOfItems + 1);

for (var i = 0; i < dp.length; i++) {
// Placing an array at each index of dp to make it a 2d matrix
dp[i] = new Array(totalWeight + 1);
}

// Loop traversing each state of dp
for (var i = 0; i < numberOfItems; i++) {
for (var j = 0; j <= totalWeight; j++) {
if (i == 0) {
if (j >= weights[i]) {
// grab the first item if it's weight is less than remaining weight (j)
dp[i][j] = values[i];
continue;
}
// if weight[i] is more than remaining weight (j) leave it
dp[i][j] = 0;
continue;
}

if (j < weights[i]) {
// weight of current item (weights[i]) is more than remaining weight (j), leave the current item and just carry on previous items
dp[i][j] = dp[i - 1][j];
continue;
}
// select the maximum of (if current weight is collected thus adding it's value) and (if current weight is not collected thus not adding it's value)
dp[i][j] = Math.max(dp[i - 1][j - weights[i]] + values[i], dp[i - 1][j]);
}
}

// Return the final maximized value at last position of dp matrix
return dp[numberOfItems - 1][totalWeight];
};
36 changes: 36 additions & 0 deletions dynamic_programing/test/Knapsack.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { knapsack } from "../Knapsack";

describe("Knapsack Algorithm Test", () => {
it("test 1 : Should be equal to 17", () => {
var values = [5, 6, 4, 6, 5, 2];
var weights = [6, 5, 6, 6, 3, 7];
var totalWeight = 15;
var numberOfItems = values.length;
expect(knapsack(numberOfItems, totalWeight, weights, values)).toBe(17);
});

it("test 2 : Should be equal to 220", () => {
var values = [60, 100, 120];
var weights = [10, 20, 30];
var totalWeight = 50;
var numberOfItems = values.length;
expect(knapsack(numberOfItems, totalWeight, weights, values)).toBe(220);
});
it("test 3 : Should be equal to 90", () => {
var values = [30, 50, 60];
var weights = [3, 4, 5];
var totalWeight = 8;
var numberOfItems = values.length;
expect(knapsack(numberOfItems, totalWeight, weights, values)).toBe(90);
});
it("test 4 : Should be equal to 5000000000", () => {
var values = [1000000000, 1000000000, 1000000000, 1000000000, 1000000000];
var weights = [1, 1, 1, 1, 1];

var totalWeight = 5;
var numberOfItems = values.length;
expect(knapsack(numberOfItems, totalWeight, weights, values)).toBe(
5000000000
);
});
});