crypto_square started
This commit is contained in:
31
elixir/crypto-square/lib/crypto_square.ex
Normal file
31
elixir/crypto-square/lib/crypto_square.ex
Normal file
@@ -0,0 +1,31 @@
|
||||
defmodule CryptoSquare do
|
||||
@doc """
|
||||
Encode string square methods
|
||||
## Examples
|
||||
|
||||
iex> CryptoSquare.encode("abcd")
|
||||
"ac bd"
|
||||
"""
|
||||
@spec encode(String.t()) :: String.t()
|
||||
def encode(str) do
|
||||
str
|
||||
|> normalize()
|
||||
|> square()
|
||||
end
|
||||
|
||||
defp normalize(str) do
|
||||
str
|
||||
|> String.downcase()
|
||||
|> String.replace(~r/[^a-z0-9]/, "")
|
||||
end
|
||||
|
||||
defp square(str) do
|
||||
length = String.length(str)
|
||||
row = :math.ceil(length ** 0.5)
|
||||
col = :math.ceil(length / row)
|
||||
|
||||
str
|
||||
|> String.split("", trim: true)
|
||||
|> Enum.chunk_every(col, col)
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user