호두나무 공방/Exercism in Elixir

Allergies - Exercism in Elixir

2022. 7. 26. 23:32

문제 보기

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