Created
May 22, 2015 15:12
-
-
Save someword/a871b1a0d616e8755742 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example usage: | |
# | |
# pry(main)> o = Allergies.new(0) | |
#=> #<Allergies:0x007f8a67b88190 @allergy_list=[]> | |
#[3] pry(main)> o.list | |
#=> [] | |
#[4] pry(main)> o = Allergies.new(6) | |
#=> #<Allergies:0x007f8a660210a0 @allergy_list=[4, 2]> | |
#[5] pry(main)> o.allergic_to?('shellfish') | |
#=> true | |
#[6] pry(main)> o.allergic_to?('work') | |
#=> false | |
#[7] pry(main)> o.list | |
#=> ["peanuts", "shellfish"] | |
# | |
class Allergies | |
ALLERGY_TABLE = { | |
'eggs' => 1, | |
'peanuts' => 2, | |
'shellfish' => 4, | |
'strawberries' => 8, | |
'tomatoes' => 16, | |
'chocolate' => 32, | |
'pollen' => 64, | |
'cats' => 128 | |
} | |
def initialize(allergy_score) | |
@allergy_list = get_allergy_list(allergy_score) | |
end | |
def allergic_to?(item) | |
(ALLERGY_TABLE.keys & list).include?(item) | |
end | |
def list | |
@allergy_list.reverse.sort.each_with_object([]) do |value, array| | |
array.push(ALLERGY_TABLE.key(value)) if ALLERGY_TABLE.key(value) | |
end | |
end | |
private | |
def get_allergy_list(score) | |
results = [] | |
return results if score.zero? | |
case power_of_two?(score) | |
when true | |
results.push(score) | |
else | |
get_remainder_and_other(score).each do |number| | |
get_allergy_list(number).each { |result| results.push(result) } | |
end | |
results | |
end | |
results | |
end | |
def power_of_two?(number) | |
number & (number - 1) == 0 | |
end | |
def get_remainder_and_other(number) | |
remainder = (number & (number - 1)) | |
other = number - remainder | |
[remainder, other] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment