exercism/elixir/crypto-square/lib/crypto_square.ex

32 lines
570 B
Elixir
Raw Permalink Normal View History

2024-08-22 14:12:28 +00:00
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