Skip to content

Commit f850428

Browse files
committed
start divide and conquer
1 parent 2cfac1b commit f850428

File tree

4 files changed

+21
-16
lines changed

4 files changed

+21
-16
lines changed

book/book.adoc

+4
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,12 @@ include::chapters/greedy-algorithms--knapsack-problem.adoc[]
183183
184184
= Divide and Conquer Algorithms
185185
186+
include::chapters/divide-and-conquer--intro.adoc[]
187+
188+
186189
:leveloffset: +1
187190
191+
188192
:leveloffset: -1
189193
190194
= Backtracking Algorithms

book/chapters/greedy-algorithms--knapsack-problem.adoc

+4
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,7 @@ Let's implement this algorithm!
4848
----
4949
include::{codedir}/algorithms/knapsack-fractional.js[tag=snippet,indent=0]
5050
----
51+
52+
What's the runtime of this algorithm?
53+
54+
We have to sort the array based on value/weight ratio. Sorting runtime is O(n log n). The rest is linear operations, so we the answer is _O(n log n)_ for our greedy algorithm.

book/chapters/sample.adoc

+4
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,10 @@ BigInt allows to operate beyond the maximum safe limit of integers (Number.MAX_S
7575
- <<Adaptive>>: [big]#✅# Yes
7676
- Time Complexity: [big]#⛔️# <<Quadratic>> _O(n^2^)_
7777

78+
.How to explain dynamic programming to kids? 👶
79+
----
80+
test [big]*🤯*
81+
----
7882

7983
== Images
8084

src/algorithms/knapsack-fractional.js

+9-16
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// tag::snippet[]
22
/**
3-
*
3+
* Solves Bounded Knapsack Problem (BKP)
4+
* You can take fractions or whole part of items.
45
* @param {Array} input array of objects with the shape {value, weight}
56
* @param {Number} max maximum weight for knapsack
67
*/
@@ -16,25 +17,17 @@ function solveFractionalKnapsack(input, max) {
1617
const bestRatioItem = input.pop();
1718

1819
if (weight + bestRatioItem.weight <= max) {
19-
// take item as a whole
20-
bestRatioItem.proportion = 1;
21-
items.push(bestRatioItem);
22-
weight += bestRatioItem.weight;
23-
value += bestRatioItem.value;
24-
} else {
25-
// take a fraction of the item
20+
bestRatioItem.proportion = 1; // take item as a whole
21+
} else { // take a fraction of the item
2622
bestRatioItem.proportion = (max - weight) / bestRatioItem.weight;
27-
items.push(bestRatioItem);
28-
weight += bestRatioItem.proportion * bestRatioItem.weight;
29-
value += bestRatioItem.proportion * bestRatioItem.value;
3023
}
24+
25+
items.push(bestRatioItem);
26+
weight += bestRatioItem.proportion * bestRatioItem.weight;
27+
value += bestRatioItem.proportion * bestRatioItem.value;
3128
}
3229

33-
return {
34-
weight,
35-
value,
36-
items,
37-
};
30+
return { weight, value, items };
3831
}
3932
// end::snippet[]
4033

0 commit comments

Comments
 (0)