Skip to content

Commit bf7d9df

Browse files
authored
Adding implementation of knapsack
1 parent af40ff3 commit bf7d9df

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

dynamic_programming/knapsack.rb

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
require "test/unit"
2+
3+
# 0-1 Knapsack problem
4+
# The function returns the maximum value that can be put in a knapsack of a given capacity
5+
6+
def knapSack(weight, wt, val, n)
7+
8+
rows, cols = n+1,weight+1
9+
# Create a 2D array to store results of subproblems
10+
dp = Array.new(rows) { Array.new(cols) }
11+
12+
for i in (0..n + 1-1)
13+
for w in (0..weight + 1-1)
14+
# if the weight is 0 or value is zero, the corresponding cell in the 2D array is set to 0
15+
if i == 0 || w == 0
16+
dp[i][w] = 0
17+
18+
#If the weight of an element is less than the capacity of the bag, the maximum value of the two cases is taken(Either the element is taken into consideration
19+
#or is ignored)
20+
elsif wt[i-1] <= w
21+
dp[i][w] = [ val[i-1] + dp[i-1][w-wt[i-1]],dp[i-1][w]].max()
22+
23+
#If the weight of the element is greater than the capacity of the bag, the cell is set to the value of the previous cell
24+
else
25+
dp[i][w] = dp[i-1][w]
26+
end
27+
end
28+
end
29+
30+
return dp[n][weight]
31+
end
32+
33+
34+
35+
36+
37+
class Knapsacktest < Test::Unit::TestCase
38+
39+
#Test1
40+
def test_knapsack1
41+
assert_equal 220, knapSack(50,[10,20,30],[60,100,120],3), "Should return 220"
42+
end
43+
44+
45+
#Test2
46+
def test_knapsack2
47+
assert_equal 500, knapSack(50,[50, 20, 30],[100, 200, 300],3), "Should return 500"
48+
end
49+
50+
#Test3
51+
def test_knapsack3
52+
assert_equal 17, knapSack(10,[3,4,5, 2, 1],[10,2,3,4,0],5), "Should return 17"
53+
end
54+
55+
#Test4
56+
def test_knapsack4
57+
assert_equal 0, knapSack(0,[23, 17, 12, 8, 20],[199,200,30,41,10],5), "Should return 0"
58+
end
59+
60+
61+
end
62+
63+
64+

0 commit comments

Comments
 (0)