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(""), do: "" defp square(str) do length = String.length(str) row = round(ceil(length ** 0.5)) str |> String.split("", trim: true) |> Enum.chunk_every(row, row, List.duplicate(" ", row)) |> Enum.zip() |> Enum.map(&Tuple.to_list(&1)) |> Enum.map_join(" ", &Enum.join(&1)) end end