crypto-square

This commit is contained in:
Danil Negrienko 2025-04-25 13:42:24 -04:00
parent ab3508e9fc
commit 5f594b12e3
2 changed files with 7 additions and 11 deletions

View File

@ -19,13 +19,17 @@ defmodule CryptoSquare do
|> String.replace(~r/[^a-z0-9]/, "") |> String.replace(~r/[^a-z0-9]/, "")
end end
defp square(""), do: ""
defp square(str) do defp square(str) do
length = String.length(str) length = String.length(str)
row = :math.ceil(length ** 0.5) row = round(ceil(length ** 0.5))
col = :math.ceil(length / row)
str str
|> String.split("", trim: true) |> String.split("", trim: true)
|> Enum.chunk_every(col, col) |> Enum.chunk_every(row, row, List.duplicate(" ", row))
|> Enum.zip()
|> Enum.map(&Tuple.to_list(&1))
|> Enum.map_join(" ", &Enum.join(&1))
end end
end end

View File

@ -1,42 +1,34 @@
defmodule CryptoSquareTest do defmodule CryptoSquareTest do
use ExUnit.Case use ExUnit.Case
# @tag :pending
test "empty plaintext results in an empty ciphertext" do test "empty plaintext results in an empty ciphertext" do
assert CryptoSquare.encode("") == "" assert CryptoSquare.encode("") == ""
end end
@tag :pending
test "normalization results in empty plaintext" do test "normalization results in empty plaintext" do
assert CryptoSquare.encode("... --- ...") == "" assert CryptoSquare.encode("... --- ...") == ""
end end
@tag :pending
test "lowercase" do test "lowercase" do
assert CryptoSquare.encode("A") == "a" assert CryptoSquare.encode("A") == "a"
end end
@tag :pending
test "remove spaces" do test "remove spaces" do
assert CryptoSquare.encode(" b ") == "b" assert CryptoSquare.encode(" b ") == "b"
end end
@tag :pending
test "remove punctuation" do test "remove punctuation" do
assert CryptoSquare.encode("@1,%!") == "1" assert CryptoSquare.encode("@1,%!") == "1"
end end
@tag :pending
test "9 character plaintext results in 3 chunks of 3 characters" do test "9 character plaintext results in 3 chunks of 3 characters" do
assert CryptoSquare.encode("This is fun!") == "tsf hiu isn" assert CryptoSquare.encode("This is fun!") == "tsf hiu isn"
end end
@tag :pending
test "8 character plaintext results in 3 chunks, the last one with a trailing space" do test "8 character plaintext results in 3 chunks, the last one with a trailing space" do
assert CryptoSquare.encode("Chill out.") == "clu hlt io " assert CryptoSquare.encode("Chill out.") == "clu hlt io "
end end
@tag :pending
test "54 character plaintext results in 7 chunks, the last two with trailing spaces" do test "54 character plaintext results in 7 chunks, the last two with trailing spaces" do
msg = "If man was meant to stay on the ground, god would have given us roots." msg = "If man was meant to stay on the ground, god would have given us roots."
cipher = "imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau " cipher = "imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau "