Avatar of davearonson

davearonson's solution

to Crypto Square in the Elixir Track

Published at Jul 13 2018 · 1 comment
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Implement the classic method for composing secret messages called a square code.

Given an English text, output the encoded version of that text.

First, the input is normalized: the spaces and punctuation are removed from the English text and the message is downcased.

Then, the normalized characters are broken into rows. These rows can be regarded as forming a rectangle when printed with intervening newlines.

For example, the sentence

If man was meant to stay on the ground, god would have given us roots.

is normalized to:

ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots

The plaintext should be organized in to a rectangle. The size of the rectangle (r x c) should be decided by the length of the message, such that c >= r and c - r <= 1, where c is the number of columns and r is the number of rows.

Our normalized text is 54 characters long, dictating a rectangle with c = 8 and r = 7:

ifmanwas
meanttos
tayonthe
groundgo
dwouldha
vegivenu
sroots

The coded message is obtained by reading down the columns going left to right.

The message above is coded as:

imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau

Output the encoded text in chunks. Phrases that fill perfect rectangles (r X c) should be output c chunks of r length, separated by spaces. Phrases that do not fill perfect rectangles will have n empty spaces. Those spaces should be distributed evenly, added to the end of the last n chunks.

imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn  sseoau 

Notice that were we to stack these, we could visually decode the cyphertext back in to the original message:

imtgdvs
fearwer
mayoogo
anouuio
ntnnlvt
wttddes
aohghn
sseoau

Running tests

Execute the tests with:

$ elixir crypto_square_test.exs

Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by commenting out the relevant @tag :pending with a # symbol.

For example:

# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end

Or, you can enable all the tests by commenting out the ExUnit.configure line in the test suite.

# ExUnit.configure exclude: :pending, trace: true

For more detailed information about the Elixir track, please see the help page.

Source

J Dalbey's Programming Practice problems http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

crypto_square_test.exs

if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("crypto_square.exs", __DIR__)
end

ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)

defmodule CryptoSquareTest do
  use ExUnit.Case

  # @tag :pending
  test "empty string" do
    assert CryptoSquare.encode("") == ""
  end

  @tag :pending
  test "perfect square" do
    assert CryptoSquare.encode("abcd") == "ac bd"
  end

  @tag :pending
  test "uppercase string" do
    assert CryptoSquare.encode("ABCD") == "ac bd"
  end

  @tag :pending
  test "small imperfect square" do
    assert CryptoSquare.encode("This is easy") == "tis hsy ie sa"
  end

  @tag :pending
  test "punctuation and numbers" do
    assert CryptoSquare.encode("1, 2, 3, Go! Go, for God's sake!") == "1gga 2ook 3fde gos ors"
  end

  @tag :pending
  test "long string" do
    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"
    assert CryptoSquare.encode(msg) == cipher
  end
end
defmodule CryptoSquare do
  @doc """
  Encode string square methods
  ## Examples

    iex> CryptoSquare.encode("abcd")
    "ac bd"
  """
  @spec encode(String.t) :: String.t
  def encode(""), do: ""
  def encode(str) do
    chars = Regex.scan(~r/[a-zA-Z0-9]/, str |> String.downcase)
    {_, cols} = best_size(length(chars))
    chars
    |> Enum.map(&List.first/1)
    |> Enum.chunk(cols, cols, [])
    |> zip_all
    |> Enum.map(&Enum.join/1)
    |> Enum.join(" ")
  end

  # could start at {1,1}, but this lets us skip past
  # solutions that are obviously too small
  defp best_size(len) do
    root = trunc(:math.sqrt(len))
    best_size(len, {root,root})
  end
  defp best_size(len, {rows, cols}) when rows * cols >= len, do: {rows, cols}
  defp best_size(len, {rows, rows}), do: best_size(len, {rows , rows+1})
  defp best_size(len, {rows, cols}), do: best_size(len, {rows+1, cols})

  defp zip_all(lists      , acc \\ [])
  defp zip_all([]         , acc), do: acc
  defp zip_all([next|rest], acc), do: zip_all(rest, my_zip(acc, next))

  # normal zip stops at the first empty one, and this one doesn't,
  # plus it skips the conversion from nested tuples to one list.
  defp my_zip(one    , two    , acc \\ [])
  defp my_zip([]     , []     , acc), do: acc |> Enum.reverse
  defp my_zip([h1|t1], [h2|t2], acc), do: my_zip(t1, t2, [[h1,h2]|acc])
  defp my_zip([h1|t1], []     , acc), do: my_zip(t1, [], [h1|acc])
  defp my_zip([]     , [h2|t2], acc), do: my_zip([], t2, [h2|acc])

end

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of davearonson

Decided to apply the same concept to zip_all... but now that required having a "first list is empty" case for my_zip. Probably shouldn't have done this, as the old zip_all/2 was doing more than just adding an accumulator....

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?