Pastey Exorcism Tutorial: Allergies

-- a patient has a score of 34 because of peanut and chocolate allergies
-- given an allergy score, what are the `allergens` ? 
 
sequence allergens = {          -- value to add to create `score` 
"eggs",                         -- 1 
"peanuts",                      -- 2 
"shellfish",                    -- 4 
"strawberries",                 -- 8 
"tomatoes",                     -- 16 
"chocolate",                    -- 32   
"pollen",                       -- 64 
"cats",                         -- 128 
$ } 
 
integer score = 34 
 
object binscore = int_to_bits(score,8) 
     ? binscore                       --> {0,1,0,0,0,1,0,0} 
                                      --     |       | 
                                      --     peanuts chocolate 
 
for i=1 to length(binscore) do 
    if binscore[i] then 
        ? allergens[i] 
    end if 
end for 
 
--> peanuts 
--> chocolate 
 
----  
 
procedure report( atom score ) 
    object binscore = int_to_bits(score,8) 
    for i=1 to length(binscore) do 
        if binscore[i] then 
            ? allergens[i] 
        end if 
    end for 
end procedure 
 
report( 1 ) 
report( 257 ) 

1. Comment by petelomax 2 weeks ago

Phix method:

constant allergens = {{#00, "<nothing>"}, 
                      {#01, "eggs"}, 
                      {#02, "peanuts"}, 
                      {#04, "shellfish"}, 
                      {#08, "strawberries"}, 
                      {#10, "tomatoes"}, 
                      {#20, "chocolate"}, 
                      {#40, "pollen"}, 
                      {#80, "cats"}, 
                      {#100, ""}} 
 
?decode_flags(allergens,34,", ") -- "peanuts, chocolate" 
?decode_flags(allergens,0,", ") -- "<nothing>" 
?decode_flags(allergens,1,", ") -- "eggs" 
?decode_flags(allergens,257) -- "eggs" 
-- Note that without the express ignore of bit #100, or an explicit and_bits(#FF,257), you would get "0x100+eggs" 
-- (In 0.8.2+ you can specify eg #FF00 on that last line to catch any of those bits.) 
-- Leaving out the #0,"<nothing>" from allergens would make the second test yield "". 
-- I would recommend always expressing bit fields in hex for improved clarity, eg 34==#22, 257==#101.