 # davidw97's solution

## to Crypto Square in the C++ Track

Published at Aug 27 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.h

``````#ifndef CRYPTO_SQUARE_CRYPTO_SQUARE_H
#define CRYPTO_SQUARE_CRYPTO_SQUARE_H

#include <utility>
#include "vector"
#include "string"

namespace crypto_square
{
using namespace std;

class cipher
{
public:
explicit cipher(string input)
{
_input = sanitize(std::move(input));
_cipher = encode();
}

string normalize_plain_text()
{
return _input;
}
vector<string> plain_text_segments();
string normalized_cipher_text();
string cipher_text();

private:
string _input;
vector<string> _cipher;

static string sanitize(string input);
vector<string> encode();
};
}

#endif //CRYPTO_SQUARE_CRYPTO_SQUARE_H``````

### crypto_square.cpp

``````#include "crypto_square.h"
#include <cmath>

/**
* Copy cipher and return an identical cipher with trailing spaces removed from last word
*
* @return  The _cipher copy
*/
crypto_square::vector<crypto_square::string> crypto_square::cipher::plain_text_segments()
{
if (_cipher.empty())
return _cipher;

// Copy cipher
vector<string> plain_text = _cipher;
string* last_phrase = &plain_text[plain_text.size() - 1];
string::iterator itr = last_phrase->end();

--itr;
while (*itr == ' ') {
last_phrase->pop_back();
--itr;
}

return plain_text;
}

/**
* Get the text from the crypto square by adding characters column-wise (without padding spaces)
*
* @return  encoded string
*/
crypto_square::string crypto_square::cipher::cipher_text()
{
if (_cipher.empty())
return "";

string encoded;

// Add to string and remove spaces
for (size_t col = 0; col < _cipher.length(); ++col) {
for (string& row : _cipher) {
char letter = row[col];
if (letter != ' ')
encoded += row[col];
}
}

return encoded;
}

/**
* Get cipher text with spaces between each column of the cipher
*
* @return  encoded string with spaces
*/
crypto_square::string crypto_square::cipher::normalized_cipher_text()
{
if (_cipher.empty())
return "";

string encoded;

for (size_t col = 0; col < _cipher.length(); ++col) {
for (string& row : _cipher) {
encoded += row[col];
}
encoded += " ";
}

// Remove last space
encoded.pop_back();

return encoded;
}

/**
* Remove all non-alphanumeric characters from an input string
*
* @param input String to sanitize
* @return  Sanitized string
*/
crypto_square::string crypto_square::cipher::sanitize(string input)
{
string sanitized_string;

for (char c: input) {
if (isalnum(c))
sanitized_string += tolower(c);
}

return sanitized_string;
}

/**
* Encode the input string into a crypto square
*
* @return  The crypto square, stored in a vector of strings
*/
crypto_square::vector<crypto_square::string> crypto_square::cipher::encode() {
vector<string> cipher;
string input_copy = _input;
int input_length = (int) input_copy.length();
int m; int n;
float sqrt_len = sqrt(input_length);

if (sqrt_len != 0) {
sqrt_len = (int) ceil(sqrt_len);

if (input_length <= (sqrt_len * (sqrt_len - 1))) {
m = sqrt_len;
n = sqrt_len - 1;
} else {
m = sqrt_len;
n = sqrt_len;
}

while (input_length < m * n) {
input_copy += " ";
++input_length;
}

// Split into substrings
for (int i = 0; i < n; ++i) {
cipher.push_back(input_copy.substr((i * m), m));
}

return cipher;

} else {

return vector<string>();

}
}``````