From 43f587a9101dbc0e4322ae633bf75d3925e6cb0e Mon Sep 17 00:00:00 2001 From: Truong Nhan Nguyen Date: Sun, 7 Apr 2024 15:37:35 +0700 Subject: [PATCH 1/3] ref: improve code readability, maintainabiity and edge case handling - Correctly throws an error if the length of the `weights` and `values` arrays are not equal - Use camelCase consistently through the codebase - Add type annotations to the function params and return types - Adding comments within the loops to clarify the logic - Ensure the function handles edge cases appropriately, such as when capacity is 0 or when weights and values arrays are empty --- dynamic_programming/knapsack.ts | 52 +++++++++++++-------------------- 1 file changed, 21 insertions(+), 31 deletions(-) diff --git a/dynamic_programming/knapsack.ts b/dynamic_programming/knapsack.ts index 853e50ab..45aca19b 100644 --- a/dynamic_programming/knapsack.ts +++ b/dynamic_programming/knapsack.ts @@ -13,44 +13,34 @@ export const knapsack = ( capacity: number, weights: number[], values: number[] -) => { - if (weights.length != values.length) { - throw new Error( - 'weights and values arrays should have same number of elements' - ) +): number => { + if (weights.length !== values.length) { + throw new Error('Weights and values arrays should have the same number of elements'); } - const numberOfItems = weights.length + const numberOfItems: number = weights.length; - // Declaring a data structure to store calculated states/values - const dp: number[][] = new Array(numberOfItems + 1) - - for (let i = 0; i < dp.length; i++) { - // Placing an array at each index of dp to make it a 2d matrix - dp[i] = new Array(capacity + 1) - } + // Initializing a 2D array to store calculated states/values + const dp: number[][] = new Array(numberOfItems + 1).fill(0).map(() => new Array(capacity + 1).fill(0)); // Loop traversing each state of dp - for (let i = 0; i < numberOfItems; i++) { - for (let j = 0; j <= capacity; 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] - } else { - // if weight[i] is more than remaining weight (j) leave it - dp[i][j] = 0 - } - } else if (j < weights[i]) { - // if 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] + for (let itemIndex = 1; itemIndex <= numberOfItems; itemIndex++) { + const weight = weights[itemIndex - 1]; + const value = values[itemIndex - 1]; + for (let currentCapacity = 1; currentCapacity <= capacity; currentCapacity++) { + if (weight <= currentCapacity) { + // Select the maximum value of including the current item or excluding it + dp[itemIndex][currentCapacity] = Math.max( + value + dp[itemIndex - 1][currentCapacity - weight], + dp[itemIndex - 1][currentCapacity] + ); } else { - // 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]) + // If the current item's weight exceeds the current capacity, exclude it + dp[itemIndex][currentCapacity] = dp[itemIndex - 1][currentCapacity]; } } } - // Return the final maximized value at last position of dp matrix - return dp[numberOfItems - 1][capacity] -} + // Return the final maximized value at the last position of the dp matrix + return dp[numberOfItems][capacity]; +}; \ No newline at end of file From d7cd7689e55493b13b79693334d30b7a20d37dc9 Mon Sep 17 00:00:00 2001 From: Truong Nhan Nguyen Date: Sun, 7 Apr 2024 15:38:07 +0700 Subject: [PATCH 2/3] chore(docs): rewrite function docstring --- dynamic_programming/knapsack.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/dynamic_programming/knapsack.ts b/dynamic_programming/knapsack.ts index 45aca19b..63baaa03 100644 --- a/dynamic_programming/knapsack.ts +++ b/dynamic_programming/knapsack.ts @@ -1,14 +1,14 @@ /** - * @function knapsack - * @description Given weights and values of n (numberOfItems) items, put these items in a knapsack of capacity 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 capacity 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 capacity. 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 (independent of input) : O(numberOfItems * capacity) - * - * @return maximum value subset of values[] such that sum of the weights of this subset is smaller than or equal to capacity. - * @see [Knapsack](https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/) - * @example knapsack(3, 8, [3, 4, 5], [30, 50, 60]) = 90 + * Solves the 0-1 Knapsack Problem. + * @param capacity Knapsack capacity + * @param weights Array of item weights + * @param values Array of item values + * @returns Maximum value subset such that sum of the weights of this subset is smaller than or equal to capacity + * @throws If weights and values arrays have different lengths + * @see [Knapsack](https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/) + * @example knapsack(3, [3, 4, 5], [30, 50, 60]) // Output: 90 */ + export const knapsack = ( capacity: number, weights: number[], From c0702601513a766636bc5f27eba6dc9aae3cfaa1 Mon Sep 17 00:00:00 2001 From: Truong Nhan Nguyen Date: Sun, 7 Apr 2024 15:58:42 +0700 Subject: [PATCH 3/3] style: format code using prettier --- dynamic_programming/knapsack.ts | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/dynamic_programming/knapsack.ts b/dynamic_programming/knapsack.ts index 63baaa03..0bc51012 100644 --- a/dynamic_programming/knapsack.ts +++ b/dynamic_programming/knapsack.ts @@ -15,32 +15,40 @@ export const knapsack = ( values: number[] ): number => { if (weights.length !== values.length) { - throw new Error('Weights and values arrays should have the same number of elements'); + throw new Error( + 'Weights and values arrays should have the same number of elements' + ) } - const numberOfItems: number = weights.length; + const numberOfItems: number = weights.length // Initializing a 2D array to store calculated states/values - const dp: number[][] = new Array(numberOfItems + 1).fill(0).map(() => new Array(capacity + 1).fill(0)); + const dp: number[][] = new Array(numberOfItems + 1) + .fill(0) + .map(() => new Array(capacity + 1).fill(0)) // Loop traversing each state of dp for (let itemIndex = 1; itemIndex <= numberOfItems; itemIndex++) { - const weight = weights[itemIndex - 1]; - const value = values[itemIndex - 1]; - for (let currentCapacity = 1; currentCapacity <= capacity; currentCapacity++) { + const weight = weights[itemIndex - 1] + const value = values[itemIndex - 1] + for ( + let currentCapacity = 1; + currentCapacity <= capacity; + currentCapacity++ + ) { if (weight <= currentCapacity) { // Select the maximum value of including the current item or excluding it dp[itemIndex][currentCapacity] = Math.max( value + dp[itemIndex - 1][currentCapacity - weight], dp[itemIndex - 1][currentCapacity] - ); + ) } else { // If the current item's weight exceeds the current capacity, exclude it - dp[itemIndex][currentCapacity] = dp[itemIndex - 1][currentCapacity]; + dp[itemIndex][currentCapacity] = dp[itemIndex - 1][currentCapacity] } } } // Return the final maximized value at the last position of the dp matrix - return dp[numberOfItems][capacity]; -}; \ No newline at end of file + return dp[numberOfItems][capacity] +}