diff --git a/exhaustive-search.md b/exhaustive-search.md index bf3704f12ed4120e0d8c447644e7d99e630a8301..ec3baf63935477371a94613d4f1d7c101a1f7c75 100644 --- a/exhaustive-search.md +++ b/exhaustive-search.md @@ -113,22 +113,24 @@ set of items not exceeding the weight limit. Signature: knapsack(I: set<item>, w: set<item> → number, W: number, v: set<item> → number) → K: set<item> Happy path: - Precondition: - Postcondition: - Postcondition: + Precondition: |options(I, w, W)| > 0 + Postcondition: K ∈ options(I, w, W) + Postcondition: ∀X∈options(I, w, W). v(K) ≥ v(X) Sad path: - Precondition: - Postcondition: + Precondition: |options(I, w, W)| = 0 + Postcondition: K = ⊥ ### JavaScript ``` function knapsack(items, getWeight, weightLimit, getValue) { - // … + let result = undefined; for (const option of options(items, getWeight, weightLimit)) { - // … + if (result === undefined || getValue(option) >= getValue(result)) { + result = option; + } } - // … + return result; } ``` @@ -144,13 +146,19 @@ of items not exceeding the weight limit. Signature: options(I: set<item>, w: set<item> → number, W: number) → O: set<set<item>> Precondition: [none] -Postcondition: -Postcondition: +Postcondition: O ⊆ 𝒫(I) +Postcondition: ∀X∈𝒫(I). X∈O ↔ w(X) ≤ W #### JavaScript ``` function options(items, getWeight, weightLimit) { - // … + const results = new Set(); + for (const candidate of powerset(items)) { + if (getWeight(candidate) <= weightLimit) { + results.add(candidate); + } + } + return results; } ```