exercism/elixir/pop-count/lib/pop_count.ex

52 lines
1.1 KiB
Elixir
Raw Normal View History

2023-12-21 04:21:06 +00:00
defmodule PopCount do
@doc """
Given the number, count the number of eggs.
"""
@spec egg_count(number :: integer()) :: non_neg_integer()
def egg_count(number) do
for(<<bit::1 <- :binary.encode_unsigned(number)>>, do: bit) |> Enum.sum
end
# @spec egg_count(number :: integer()) :: non_neg_integer()
# def egg_count(number) do
# result =
# number
# |> Integer.digits(2)
# |> Enum.reduce(%{binary: "", count: 0, coop: "|", length: 0}, &egg_counter/2)
# """
# Chicken Coop:
# #{String.duplicate(" _", result.length)}
# #{result.coop}
# Resulting Binary:
# #{result.binary}
# Decimal number on the display:
# #{number}
# Actual eggs in the coop:
# #{result.count}
# """
# |> IO.puts()
# result.count
# end
# defp egg_counter(element, %{binary: binary, count: count, coop: coop, length: length} = _acc) do
# char =
# case element do
# 0 -> " "
# 1 -> "E"
# end
# %{
# coop: coop <> char <> "|",
# count: count + element,
# length: length + 1,
# binary: binary <> "#{element}"
# }
# end
end