|
| 1 | +def knapsack_rec(weights, values, capacity, length) |
| 2 | + return 0 if length.zero? || capacity.zero? |
| 3 | + |
| 4 | + # if weight is more than the capacity, so can't be included |
| 5 | + return knapsack_rec(weights, values, capacity, length - 1) if weights[length - 1] > capacity |
| 6 | + |
| 7 | + remaining_cap = capacity - weights[length - 1] |
| 8 | + |
| 9 | + # Max of if we include the item or don't include |
| 10 | + # If we include, we will add value also |
| 11 | + [ |
| 12 | + values[length - 1] + knapsack_rec(weights, values, remaining_cap, length - 1), |
| 13 | + knapsack_rec(weights, values, capacity, length - 1) |
| 14 | + ].max |
| 15 | +end |
| 16 | + |
| 17 | +def knapsack_dp(weights, values, capacity) |
| 18 | + return 0 if weights.empty? || capacity.zero? |
| 19 | + |
| 20 | + length = weights.length |
| 21 | + dp = Array.new(length + 1) { |_i| Array.new(capacity + 1, 0) } |
| 22 | + |
| 23 | + (1..length).each do |item| |
| 24 | + weight = weights[item - 1] |
| 25 | + value = values[item - 1] |
| 26 | + (1..capacity).each do |cap| |
| 27 | + dp[item][cap] = if weight > cap |
| 28 | + dp[item - 1][cap] |
| 29 | + else |
| 30 | + [dp[item - 1][cap], dp[item - 1][cap - weight] + value].max |
| 31 | + end |
| 32 | + end |
| 33 | + end |
| 34 | + # puts dp.to_s |
| 35 | + dp[-1][-1] |
| 36 | +end |
| 37 | +values = [60, 100, 120] |
| 38 | +weights = [10, 20, 30] |
| 39 | +capacity = 50 |
| 40 | + |
| 41 | +# puts knapsack_rec(weights, values, capacity, weights.length) #output 220 |
| 42 | + |
| 43 | +puts knapsack_dp(weights, values, capacity) # output 220 |
| 44 | + |
| 45 | +puts knapsack_dp(weights, values, capacity) # output 220 |
| 46 | + |
| 47 | +weights = [[1, 2, 3, 4, 5], [1, 3, 4, 6, 9], [1, 2, 3, 5], [3, 5]] |
| 48 | +values = [[3, 5, 4, 8, 10], [5, 10, 4, 6, 8], [1, 19, 80, 100], [80, 100]] |
| 49 | +capacities = [5, 10, 6, 2] |
| 50 | + |
| 51 | +(0..3).each do |i| |
| 52 | + puts "[DP] 0-1 Knapsack max value : #{knapsack_dp(weights[i], values[i], capacities[i])}" |
| 53 | + puts "[Recursive] 0-1 Knapsack max value : #{knapsack_rec(weights[i], values[i], capacities[i], weights[i].length)}" |
| 54 | +end |
0 commit comments