crypto_square started

This commit is contained in:
2024-08-22 10:12:28 -04:00
parent 1a4c55bdaf
commit 79f77f009a
10 changed files with 340 additions and 0 deletions

View 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