Skip to content

Commit 6dfd6fb

Browse files
committed
Recursive solution to cake thief
1 parent e8705ee commit 6dfd6fb

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
Cake = Struct.new(:weight, :value)
2+
3+
def pick_cakes(index, cakes, capacity)
4+
return 0 if index == cakes.length || capacity.zero?
5+
6+
current_cake = cakes[index]
7+
8+
return pick_cakes(index + 1, cakes, capacity) if current_cake.weight > capacity
9+
10+
using_current = current_cake.value +
11+
pick_cakes(index, cakes, capacity - current_cake.weight)
12+
13+
not_using_current = pick_cakes(index + 1, cakes, capacity)
14+
15+
[using_current, not_using_current].max
16+
end
17+
18+
def max_duffel_bag_value(cakes, capacity)
19+
pick_cakes(0, cakes, capacity)
20+
end
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
require 'minitest/autorun'
2+
require './cake_thief_recursion'
3+
4+
class CakeThiefRecursionTest < Minitest::Test
5+
6+
def test_zero_capacity
7+
cakes = [Cake.new(7, 160), Cake.new(3, 90), Cake.new(2, 15)]
8+
capacity = 0
9+
assert_equal 0, max_duffel_bag_value(cakes, capacity)
10+
end
11+
12+
def test_zero_cakes
13+
cakes = []
14+
capacity = 1000
15+
assert_equal 0, max_duffel_bag_value(cakes, capacity)
16+
end
17+
18+
def test_one_cake_with_weight_equal_to_capacity
19+
cakes = [Cake.new(5, 70)]
20+
capacity = 5
21+
assert_equal 70, max_duffel_bag_value(cakes, capacity)
22+
end
23+
24+
def test_cakes_with_spare_capacity
25+
cakes = [Cake.new(3, 9), Cake.new(2, 4)]
26+
capacity = 4
27+
assert_equal 9, max_duffel_bag_value(cakes, capacity)
28+
end
29+
30+
def test_not_all_capacity_should_be_used
31+
cakes = [Cake.new(5, 25), Cake.new(4, 16)]
32+
capacity = 12
33+
assert_equal 50, max_duffel_bag_value(cakes, capacity)
34+
end
35+
36+
def test_use_the_biggest_and_the_smallest
37+
cakes = [Cake.new(3, 9), Cake.new(2, 4), Cake.new(1, 1)]
38+
capacity = 4
39+
assert_equal 10, max_duffel_bag_value(cakes, capacity)
40+
end
41+
42+
def test_use_a_really_valuable_small_cake
43+
cakes = [Cake.new(3, 9), Cake.new(2, 4), Cake.new(1, 30)]
44+
capacity = 4
45+
assert_equal 120, max_duffel_bag_value(cakes, capacity)
46+
end
47+
48+
def test_arts_test
49+
cakes = [Cake.new(3, 16), Cake.new(2, 15)]
50+
capacity = 3
51+
assert_equal 16, max_duffel_bag_value(cakes, capacity)
52+
end
53+
54+
def test_interview_cake_test
55+
cakes = [Cake.new(7, 160), Cake.new(3, 90), Cake.new(2, 15)]
56+
capacity = 20
57+
assert_equal 555, max_duffel_bag_value(cakes, capacity)
58+
end
59+
end

0 commit comments

Comments
 (0)