Skip to content

Commit 4be3acd

Browse files
committed
exercism-67 Allergies
1 parent 5cce519 commit 4be3acd

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,7 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
284284
64. [Binary Search](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/binary_search.rb)
285285
65. [Matching Brackets](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/matching_brackets.rb)
286286
66. [All Your Base](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/all_your_base.rb)
287+
67. [Allergies](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/allergies.rb)
287288

288289
<a name="leetcode"/>
289290

exercism/allergies.rb

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Problem: https://exercism.org/tracks/ruby/exercises/allergies
2+
3+
# Solution 1
4+
class Allergies
5+
ALLERGY_VAL_FOOD_MAP = {
6+
1 => 'eggs',
7+
2 => 'peanuts',
8+
4 => 'shellfish',
9+
8 => 'strawberries',
10+
16 => 'tomatoes',
11+
32 => 'chocolate',
12+
64 => 'pollen',
13+
128 => 'cats'
14+
}
15+
16+
def initialize(score)
17+
@score = score.to_s(2).reverse
18+
@allergies = []
19+
end
20+
21+
def allergic_to?(item)
22+
self.list if @allergies.empty?
23+
@allergies.include?(item)
24+
end
25+
26+
def list
27+
debug "score#{@score}"
28+
ALLERGY_VAL_FOOD_MAP.each do |key,val|
29+
@allergies.push(val) if @score[Math.log(key,2)] == '1'
30+
end
31+
@allergies
32+
end
33+
end
34+
35+
# Solution 2
36+
class Allergies
37+
ALLERGY_VAL_FOOD_MAP = {
38+
1 => 'eggs',
39+
2 => 'peanuts',
40+
4 => 'shellfish',
41+
8 => 'strawberries',
42+
16 => 'tomatoes',
43+
32 => 'chocolate',
44+
64 => 'pollen',
45+
128 => 'cats'
46+
}
47+
48+
def initialize(score)
49+
@score = score%256
50+
@list = []
51+
end
52+
53+
def allergic_to?(item)
54+
self.list if @list.empty?
55+
@list.include?(item)
56+
end
57+
58+
def list
59+
num = 2**7
60+
while num > 0
61+
if @score >= num
62+
@list.push(ALLERGY_VAL_FOOD_MAP[num])
63+
@score-=num
64+
end
65+
num/=2
66+
end
67+
@list.reverse!
68+
end
69+
end

0 commit comments

Comments
 (0)