Skip to content

Commit

Permalink
knapsack - added solution
Browse files Browse the repository at this point in the history
  • Loading branch information
m4drat committed Jan 12, 2024
1 parent 4e3e9fa commit 7532481
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ A collection of resources and code snippets for learning rust.
| 5 | Fizzy | [Link](exercism-solutions/rust/fizzy/src/lib.rs) | ⭐⭐ | ✔️ |
| 6 | Grep | [Link](exercism-solutions/rust/grep/src/lib.rs) | ||
| 7 | Hamming | [Link](exercism-solutions/rust/hamming/src/lib.rs) | ⭐⭐ | ✔️ |
| 8 | Knapsack | [Link](exercism-solutions/rust/knapsack/src/lib.rs) | | |
| 8 | Knapsack | [Link](exercism-solutions/rust/knapsack/src/lib.rs) | ⭐⭐ | ✔️ |
| 9 | Luhn-from | [Link](exercism-solutions/rust/luhn-from/src/lib.rs) | ⭐⭐ | ✔️ |
| 10 | Luhn-trait | [Link](exercism-solutions/rust/luhn-trait/src/lib.rs) | ⭐⭐ | ✔️ |
| 11 | Luhn | [Link](exercism-solutions/rust/luhn/src/lib.rs) | ⭐⭐ | ✔️ |
Expand Down
21 changes: 20 additions & 1 deletion exercism-solutions/rust/knapsack/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,24 @@ pub struct Item {
}

pub fn maximum_value(max_weight: u32, items: &[Item]) -> u32 {
todo!("calculate the maximum value achievable with the given {items:?} and {max_weight}");
let max_weight_usize = max_weight as usize;
let mut values = vec![vec![0; max_weight_usize + 1]; items.len() + 1];

for item_idx in 1..=items.len() {
let item = &items[item_idx - 1];
let weight_usize = item.weight as usize;
let value_usize = item.value as usize;

for curr_capacity in 1..=max_weight_usize {
let mut curr_value = values[item_idx - 1][curr_capacity];
if curr_capacity >= weight_usize {
curr_value = curr_value
.max(values[item_idx - 1][curr_capacity - weight_usize] + value_usize);
}

values[item_idx][curr_capacity] = curr_value;
}
}

values[items.len()][max_weight_usize] as u32
}
1 change: 1 addition & 0 deletions learning-rust.code-workspace
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"./exercism-solutions/rust/macros/Cargo.toml",
"./exercism-solutions/rust/custom-set/Cargo.toml",
"./exercism-solutions/rust/grep/Cargo.toml",
"./exercism-solutions/rust/knapsack/Cargo.toml",
"./exercism-solutions/rust/queen-attack/Cargo.toml",
"./exercism-solutions/rust/simple-linked-list/Cargo.toml",
"./rust-book/book/Cargo.toml",
Expand Down

0 comments on commit 7532481

Please sign in to comment.