all_your_base
This commit is contained in:
31
elixir/all-your-base/lib/all_your_base.ex
Normal file
31
elixir/all-your-base/lib/all_your_base.ex
Normal file
@@ -0,0 +1,31 @@
|
||||
defmodule AllYourBase do
|
||||
@doc """
|
||||
Given a number in input base, represented as a sequence of digits, converts it to output base,
|
||||
or returns an error tuple if either of the bases are less than 2
|
||||
"""
|
||||
|
||||
@spec convert(list, integer, integer) :: {:ok, list} | {:error, String.t()}
|
||||
def convert(_digits, input_base, _output_base) when input_base < 2,
|
||||
do: {:error, "input base must be >= 2"}
|
||||
|
||||
def convert(_digits, _input_base, output_base) when output_base < 2,
|
||||
do: {:error, "output base must be >= 2"}
|
||||
|
||||
def convert([0 | digits], input_base, output_base), do: convert(digits, input_base, output_base)
|
||||
|
||||
def convert(digits, input_base, output_base) do
|
||||
unless Enum.all?(digits, &valid_digit?(&1, input_base)) do
|
||||
{:error, "all digits must be >= 0 and < input base"}
|
||||
else
|
||||
result =
|
||||
digits
|
||||
|> Integer.undigits(input_base)
|
||||
|> Integer.digits(output_base)
|
||||
|
||||
{:ok, result}
|
||||
end
|
||||
end
|
||||
|
||||
defp valid_digit?(digit, base) when digit >= 0 and digit < base, do: true
|
||||
defp valid_digit?(_digit, _base), do: false
|
||||
end
|
||||
Reference in New Issue
Block a user