From a1d514d1c355ee264b6d1a5603f796d5f903402c Mon Sep 17 00:00:00 2001 From: Yotoko Date: Thu, 12 Oct 2023 10:26:13 +0700 Subject: [PATCH] Allergen --- src/allergies.rs | 61 ++++++++++++++++++------------------------------ 1 file changed, 23 insertions(+), 38 deletions(-) diff --git a/src/allergies.rs b/src/allergies.rs index a3e99a8..3886b09 100644 --- a/src/allergies.rs +++ b/src/allergies.rs @@ -1,54 +1,39 @@ -// Instructions -// Given a person's allergy score, determine whether or not they're allergic to a given item, -// and their full list of allergies. -// -// An allergy test produces a single numeric score which contains the information about all -// the allergies the person has (that they were tested for). -// -// The list of items (and their value) that were tested are: -// -// eggs (1) -// peanuts (2) -// shellfish (4) -// strawberries (8) -// tomatoes (16) -// chocolate (32) -// pollen (64) -// cats (128) -// So if Tom is allergic to peanuts and chocolate, he gets a score of 34. -// -// Now, given just that score of 34, your program should be able to say: -// -// Whether Tom is allergic to any one of those allergens listed above. -// All the allergens Tom is allergic to. -// Note: a given score may include allergens not listed above (i.e. allergens that score 256, 512, 1024, etc.). -// Your program should ignore those components of the score. For example, -// if the allergy score is 257, your program should only report the eggs (1) allergy. - pub struct Allergies(u32); -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum Allergen { - Eggs, - Peanuts, - Shellfish, - Strawberries, - Tomatoes, - Chocolate, - Pollen, - Cats, + Eggs = 1 << 0, + Peanuts = 1 << 1, + Shellfish = 1 << 2, + Strawberries = 1 << 3, + Tomatoes = 1 << 4, + Chocolate = 1 << 5, + Pollen = 1 << 6, + Cats = 1 << 7, } +const ALLERGENS: [Allergen; 8] = [ + Allergen::Eggs, + Allergen::Peanuts, + Allergen::Shellfish, + Allergen::Strawberries, + Allergen::Tomatoes, + Allergen::Chocolate, + Allergen::Pollen, + Allergen::Cats +]; + impl Allergies { pub fn new(score: u32) -> Self { Allergies(score) } pub fn is_allergic_to(&self, allergen: &Allergen) -> bool { - todo!("Determine if the patient is allergic to the '{allergen:?}' allergen."); + let allergen = *allergen as u32; + self.0 & allergen == allergen } pub fn allergies(&self) -> Vec { - todo!("Return the list of allergens contained within the score with which the Allergies struct was made."); + ALLERGENS.iter().filter(|allergen| self.is_allergic_to(allergen)).cloned().collect() } }