Medium 난이도 문제 중에서는 비교적 쉬운 편에 속하는 문제인데, 비트 다루기가 귀찮아서 조금 미뤄두고 있었다. 그래도 이번에는 제법 깔끔하게... 단일 파이프라인으로 해결한 것 같다.
defmodule Allergies do
@items [
{1, "eggs"},
{2, "peanuts"},
{4, "shellfish"},
{8, "strawberries"},
{16, "tomatoes"},
{32, "chocolate"},
{64, "pollen"},
{128, "cats"},
]
@doc """
List the allergies for which the corresponding flag bit is true.
"""
@spec list(non_neg_integer) :: [String.t()]
def list(flags) do
flags
|> Integer.digits(2)
|> Enum.reverse()
|> Enum.zip(@items)
|> Enum.filter(fn {d, _} -> d == 1 end)
|> Enum.map(fn {1, {_, item}} -> item end)
end
@doc """
Returns whether the corresponding flag bit in 'flags' is set for the item.
"""
@spec allergic_to?(non_neg_integer, String.t()) :: boolean
def allergic_to?(flags, item) do
item in list(flags)
end
end
'호두나무 공방 > Exercism in Elixir' 카테고리의 다른 글
Killer Sudoku Helper - Exercism in Elixir (0) | 2022.07.28 |
---|---|
Largest Series Product - Exercism in Elixir (0) | 2022.07.27 |
Isogram - Exercism in Elixir (0) | 2022.07.25 |
Perfect Numbers - Exercism in Elixir (0) | 2022.07.22 |
Prime Factors - Exercism in Elixir (0) | 2022.07.21 |