-
Notifications
You must be signed in to change notification settings - Fork 252
/
allergies.rb
69 lines (61 loc) · 1.61 KB
/
allergies.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
# Problem: https://exercism.org/tracks/ruby/exercises/allergies
# Solution 1
class Allergies
ALLERGY_VAL_FOOD_MAP = {
1 => 'eggs',
2 => 'peanuts',
4 => 'shellfish',
8 => 'strawberries',
16 => 'tomatoes',
32 => 'chocolate',
64 => 'pollen',
128 => 'cats'
}
def initialize(score)
@score = score.to_s(2).reverse
@allergies = []
end
def allergic_to?(item)
self.list if @allergies.empty?
@allergies.include?(item)
end
def list
debug "score#{@score}"
ALLERGY_VAL_FOOD_MAP.each do |key,val|
@allergies.push(val) if @score[Math.log(key,2)] == '1'
end
@allergies
end
end
# Solution 2
class Allergies
ALLERGY_VAL_FOOD_MAP = {
1 => 'eggs',
2 => 'peanuts',
4 => 'shellfish',
8 => 'strawberries',
16 => 'tomatoes',
32 => 'chocolate',
64 => 'pollen',
128 => 'cats'
}
def initialize(score)
@score = score%256
@list = []
end
def allergic_to?(item)
self.list if @list.empty?
@list.include?(item)
end
def list
num = 2**7
while num > 0
if @score >= num
@list.push(ALLERGY_VAL_FOOD_MAP[num])
@score-=num
end
num/=2
end
@list.reverse!
end
end