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

36 lines
685 B
Elixir
Raw 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
2025-04-25 17:42:24 +00:00
defp square(""), do: ""
2024-08-22 14:12:28 +00:00
defp square(str) do
length = String.length(str)
2025-04-25 17:42:24 +00:00
row = round(ceil(length ** 0.5))
2024-08-22 14:12:28 +00:00
str
|> String.split("", trim: true)
2025-04-25 17:42:24 +00:00
|> Enum.chunk_every(row, row, List.duplicate(" ", row))
|> Enum.zip()
|> Enum.map(&Tuple.to_list(&1))
|> Enum.map_join(" ", &Enum.join(&1))
2024-08-22 14:12:28 +00:00
end
end