Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c714548

Browse files
Chore: Completed Activity-5 for Day-18
1 parent c9d9b0f commit c714548

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

‎Day18/index.js

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,4 +209,43 @@ let arr8 = [2, 4, 6, 8];
209209
console.log("Merge Arrays: ", mergeArrays(arr7, arr8));
210210

211211
console.log("-------------------------------------------------");
212-
console.log("Activity 5: ");
212+
console.log("Activity 5: ");
213+
214+
// Task 10: Write a function to solve the Fibonacci sequence using dynamic programming. Log the Fibonacci numbers.
215+
216+
const fibonacci = (n) => {
217+
let fib = [0, 1];
218+
for (let i = 2; i <= n; i++) {
219+
fib[i] = fib[i - 1] + fib[i - 2];
220+
}
221+
return fib;
222+
}
223+
224+
let n = 10;
225+
console.log("Fibonacci: ", fibonacci(n));
226+
227+
// Task 11: Write a function to solve the knapsack problem using dynamic programming. Log the maximum value that can be obtained.
228+
229+
const knapsack = (weights, values, capacity) => {
230+
let n = weights.length;
231+
let dp = Array(n + 1).fill().map(() => Array(capacity + 1).fill(0));
232+
233+
for (let i = 1; i <= n; i++) {
234+
for (let w = 1; w <= capacity; w++) {
235+
if (weights[i - 1] <= w) {
236+
dp[i][w] = Math.max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]);
237+
} else {
238+
dp[i][w] = dp[i - 1][w];
239+
}
240+
}
241+
}
242+
243+
return dp[n][capacity];
244+
}
245+
246+
let weights = [2, 3, 4, 5];
247+
let values = [3, 4, 5, 6];
248+
let capacity = 5;
249+
console.log("Knapsack: ", knapsack(weights, values, capacity));
250+
251+
console.log("-------------------------------------------------");

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /