32 lines
570 B
Elixir
32 lines
570 B
Elixir
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
|