 # kroosec's solution

## to Crypto Square in the C++ Track

Published at Sep 05 2019 · 0 comments
Instructions
Test suite
Solution

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 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:

``````"imtgdvs"
"fearwer"
"mayoogo"
"anouuio"
"ntnnlvt"
"wttddes"
"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.

``````#if defined(EXERCISM_RUN_ALL_TESTS)
``````

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.

## 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.cpp

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

TEST_CASE("normalize_capitals")
{
REQUIRE("hello" == crypto_square::cipher("Hello").normalize_plain_text());
}

#if defined(EXERCISM_RUN_ALL_TESTS)
TEST_CASE("normalize_spaces")
{
REQUIRE("hithere" == crypto_square::cipher("Hi there").normalize_plain_text());
}

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

TEST_CASE("plain_text_empty")
{
const std::vector<std::string> expected{};

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

REQUIRE(expected == actual);
}

TEST_CASE("plain_text_4_characters")
{
const std::vector<std::string> expected{"ab", "cd"};

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

REQUIRE(expected == actual);
}

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

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

REQUIRE(expected == actual);
}

TEST_CASE("plain_text_segments_from_phrase")
{
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);
}

TEST_CASE("cipher_text_empty_phrase")
{
REQUIRE("" == crypto_square::cipher("").cipher_text());
}

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

TEST_CASE("normalized_cipher_text_empty")
{
REQUIRE("" == crypto_square::cipher("").normalized_cipher_text());
}

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

TEST_CASE("normalized_cipher_text_long_phrase")
{
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());
}
#endif``````

### crypto_square.cpp

``````#include "crypto_square.h"

#include <math.h>
#include <cctype>

namespace crypto_square {

size_t get_columns(size_t len) { return std::ceil(len / sqrtf(len)); }

string normalize_text(const string& text) {
string ret;
for (char c : text) {
if (std::isalpha(c) || std::isdigit(c)) ret += std::tolower(c);
}
return ret;
}

cipher::cipher(const string& text) { text_ = normalize_text(text); }

string cipher::cipher_text() const {
string ret;
if (text_.empty()) return ret;
size_t columns = get_columns(text_.size());
for (size_t i = 0; i < columns; i++) {
for (size_t j = 0; j < text_.size(); j += columns) {
if (j + i >= text_.size()) break;
ret += text_.at(j + i);
}
}
return ret;
}

string cipher::normalized_cipher_text() const {
string ret;
if (text_.empty()) return ret;
vector<string> segments = plain_text_segments();
size_t columns = get_columns(text_.size());
for (size_t i = 0; i < columns; i++) {
for (const auto& seg : segments) {
ret += i < seg.size() ? seg.at(i) : ' ';
}
ret += ' ';
}
ret.erase(ret.end() - 1);
return ret;
}

const string& cipher::normalize_plain_text() const { return text_; }

vector<string> cipher::plain_text_segments() const {
vector<string> ret;
if (text_.empty()) return ret;
auto columns = get_columns(text_.size());

for (size_t i = 0; i < text_.size(); i += columns) {
ret.push_back(text_.substr(i, columns));
}
return ret;
}

}  // namespace crypto_square``````

### crypto_square.h

``````#include <string>
#include <vector>

using std::string;
using std::vector;

namespace crypto_square {
class cipher {
public:
cipher(const string&);
const string& normalize_plain_text() const;
vector<string> plain_text_segments() const;
string cipher_text() const;
string normalized_cipher_text() const;

private:
string text_;
};
}  // namespace crypto_square``````