Sha256: e5e84e5c0b529714b378a8229fc840872c9fb4f469e8315b6ad17c2469ac1779

Contents?: true

Size: 469 Bytes

Versions: 69

Compression:

Stored size: 469 Bytes

Contents

defmodule Binary do
  def to_decimal(string) do
    if !String.match?(string, ~r{[^10]}) do
      string |> bits |> Enum.reverse() |> Enum.with_index() |> sum
    else
      0
    end
  end

  defp bits(string), do: Enum.map(Regex.scan(~r{[10]}, string), &(&1 == ["1"]))

  defp sum(bits), do: Enum.reduce(bits, 0, fn bit, acc -> acc + power_of_two(bit) end)

  defp power_of_two({false, _}), do: 0
  defp power_of_two({true, exponent}), do: :math.pow(2, exponent)
end

Version data entries

69 entries across 69 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.179 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.178 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.177 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.176 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.175 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.174 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.173 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.172 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.171 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.170 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.169 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.167 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.166 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.165 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.164 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.163 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.162 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.161 tracks/elixir/exercises/binary/example.exs
trackler-2.2.1.160 tracks/elixir/exercises/binary/example.exs