// Let's start with an easy one: sum of a sequence. ghost function Sum(s: seq): nat { if |s| == 0 then 0 else s[0] + Sum(s[1..]) } // This predicate characterizes when a chosen sequence represents a legit // subsequence of another one *and* has a claimed sum total. ghost predicate PossibleTotalVia(s: seq, total: nat, chosen: seq) { multiset(chosen) <= multiset(s) && total == Sum(chosen) } // The following hides the choice of subsequence, using existential // quantification. ghost predicate PossibleTotal(s: seq, total: nat) { exists chosen :: PossibleTotalVia(s, total, chosen) } // Now we can characterize what is the maximum possible total that does not // exceed a limit. ghost predicate MaxTotal(s: seq, limit: nat, total: nat) { && PossibleTotal(s, total) && total <= limit && forall total': nat :: PossibleTotal(s, total') && total' <= limit ==> total' <= total } function Max(a: nat, b: nat): nat { if a < b then b else a } // Now we can define our implementation with nested loops. // There won't be time to prove this one fully in an interactive class session, // but see what you can figure out to fill in proof content. method ZeroOneKnapsack(weights: array, limit: nat) returns (total: nat) ensures MaxTotal(weights[..], limit, total) { if weights.Length == 0 { return 0; } var table := new nat[weights.Length, limit+1]; var i := 0; while i < weights.Length { var j := 0; while j <= limit { if i == 0 { if weights[i] == 0 || weights[i] > j { table[i, j] := 0; } else { table[i, j] := weights[i]; } } else if weights[i] == 0 { table[i, j] := table[i-1, j]; } else if weights[i] > j { table[i, j] := table[i-1, j]; } else if table[i-1, j-weights[i]] + weights[i] > limit { table[i, j] := table[i-1, j]; } else { table[i, j] := Max(table[i-1, j-weights[i]] + weights[i], table[i-1, j]); } j := j + 1; } i := i + 1; } return table[weights.Length-1, limit]; }