Avatar of PlanetPluto

PlanetPluto's solution

to Crypto Square in the C++ Track

Published at Sep 04 2019 · 0 comments
Test suite

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:


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:

"sroots  "

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

The message above is coded as:


Output the encoded text in chunks that fill perfect rectangles (r X c), with c chunks of r length, separated by spaces. For phrases that are n characters short of the perfect rectangle, pad each of the last n chunks with a single trailing space.

"imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn  sseoau "

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

"aohghn "
"sseoau "

Getting Started

Make sure you have read the Installing and Running the Tests pages for C++ on exercism.io. This covers the basic information on setting up the development environment expected by the exercises.

Passing the Tests

Get the first test compiling, linking and passing by following the three rules of test-driven development. Create just enough structure by declaring namespaces, functions, classes, etc., to satisfy any compiler errors and get the test to fail. Then write just enough code to get the test to pass. Once you've done that, uncomment the next test by moving the following line past the next test.


This may result in compile errors as new constructs may be invoked that you haven't yet declared or defined. Again, fix the compile errors minimally to get a failing test, then change the code minimally to pass the test, refactor your implementation for readability and expressiveness and then go on to the next test.

Try to use standard C++11 facilities in preference to writing your own low-level algorithms or facilities by hand. CppReference is a wiki reference to the C++ language and standard library. If you are new to C++, but have programmed in C, beware of C traps and pitfalls.


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.


#include "crypto_square.h"
#include "test/catch.hpp"

    REQUIRE("hello" == crypto_square::cipher("Hello").normalize_plain_text());

    REQUIRE("hithere" == crypto_square::cipher("Hi there").normalize_plain_text());

    REQUIRE("123go" == crypto_square::cipher("1, 2, 3 GO!").normalize_plain_text());

    const std::vector<std::string> expected{};

    const auto actual = crypto_square::cipher("").plain_text_segments();

    REQUIRE(expected == actual);

    const std::vector<std::string> expected{"ab", "cd"};

    const auto actual = crypto_square::cipher("Ab Cd").plain_text_segments();

    REQUIRE(expected == actual);

    const std::vector<std::string> expected{"thi", "sis", "fun"};

    const auto actual = crypto_square::cipher("This is fun!").plain_text_segments();

    REQUIRE(expected == actual);

    const std::vector<std::string> expected{"ifmanwas", "meanttos", "tayonthe", "groundgo", "dwouldha", "vegivenu", "sroots"};

    const auto actual = crypto_square::cipher("If man was meant to stay on the ground, god would have given us roots.").plain_text_segments();

    REQUIRE(expected == actual);

    REQUIRE("" == crypto_square::cipher("").cipher_text());

    REQUIRE("imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau" ==
        crypto_square::cipher("If man was meant to stay on the ground, god would have given us roots.").cipher_text());

    REQUIRE("" == crypto_square::cipher("").normalized_cipher_text());

    REQUIRE("tsf hiu isn" == crypto_square::cipher("This is fun!").normalized_cipher_text());

    REQUIRE("imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn  sseoau " ==
        crypto_square::cipher("If man was meant to stay on the ground, god would have given us roots.").normalized_cipher_text());


#include <math.h>
#include "crypto_square.hpp"

namespace crypto_square
  cipher::cipher(const std::string &text)
    std::string input = text;
    input.erase(std::remove_if(input.begin(), input.end(), [](const char c) -> bool {return !std::isalnum(c);}), input.end());
    std::transform(input.begin(), input.end(), input.begin(), []( unsigned char c) {return std::tolower(c);});
    _normalized = input;
    _col = ceil(sqrtf(_normalized.length()));
  const std::vector<std::string> cipher::plain_text_segments()
      return std::vector<std::string>{};
    std::vector<std::string> segments;
    for(unsigned long c=0;c<_normalized.length();c+=_col)
      segments.push_back(_normalized.substr(c, _col));
    return segments;
  const std::string cipher::normalized_cipher_text()
      return std::string{};
    std::size_t padmod = _normalized.length() % _col;
    _normalized.append(_col - (padmod==0?_col:padmod), ' ');
    std::string normciphertext;
    for(unsigned long c=0;c<_col;c++)
      std::string str;
      for(unsigned long r=0;r<_normalized.length();r+=_col)
      normciphertext += str + ((c<_col-1) ? std::string(" ") : std::string{});
    return normciphertext;
  const std::string cipher::cipher_text()
    std::string ciphertext = normalized_cipher_text();
    ciphertext.erase(std::remove_if(ciphertext.begin(), ciphertext.end(), [](const char c) -> bool {return !std::isalnum(c);}), ciphertext.end());
    return ciphertext;


#ifndef crypto_square_hpp
#define crypto_square_hpp

#include <string>
#include <vector>

namespace crypto_square
  class cipher final
    cipher() = delete;
    explicit cipher(const std::string &text);
    const std::vector<std::string> plain_text_segments();
    const std::string cipher_text();
    const std::string normalized_cipher_text();
    const std::string normalize_plain_text() const {return _normalized;}
    std::size_t _col;
    std::string _normalized;

#endif /* crypto_square_hpp */

Community comments

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

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?