-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsplit_the_loot.rb
105 lines (81 loc) · 1.75 KB
/
split_the_loot.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
class Array
def sum
sum = 0
each do |g|
sum += g
end
sum
end
end
class SplitTheLoot
def validate (treasure)
if treasure.empty? then
return true
end
unless treasure.size() >= @number_of_pirates then
return false
end
# Verify if the sum of the gems can be divided by the pirates
unless @sum%@number_of_pirates == 0 then
return false
end
return true
end
def split (treasure, number_of_pirates)
@number_of_pirates = number_of_pirates
@sum = 0
treasure.each do |gem|
@sum += gem
end
unless validate(treasure)
return nil
end
@pirate_share = @sum/@number_of_pirates
result = []
@number_of_pirates.times do |i|
result << []
end
if(treasure.empty?)
return result
end
@number_of_pirates.times do |i|
unless split_for_pirate(treasure, i, result)
return nil
end
end
return result
end
def split_for_pirate (treasure, pirate_index, result)
banned_gems = []
while(!treasure.empty?)
next_gem = treasure.delete_at(0)
if(next_gem + result[pirate_index].sum <= @pirate_share)
result[pirate_index] << next_gem
if(result[pirate_index].sum == @pirate_share)
return true
else
another_treasure = treasure.clone
banned_gems.each do |a|
another_treasure << a
end
another_result = []
result.each do |a|
another_result << a.clone
end
if split_for_pirate(another_treasure, pirate_index, another_result)
result.clear
another_result.each do |a|
result << a
end
return true
else
banned_gems << result[pirate_index].delete_at(-1)
end
end
else
banned_gems << next_gem
end
end
return false
end
end