diff --git a/cpp/crypto-square/crypto_square.cpp b/cpp/crypto-square/crypto_square.cpp new file mode 100644 index 0000000..9ba9f1f --- /dev/null +++ b/cpp/crypto-square/crypto_square.cpp @@ -0,0 +1,87 @@ +#include "crypto_square.h" + +#include +#include + +namespace crypto_square { + +using namespace std; + +cipher::cipher(const string &text) +{ + text_.reserve(text.size()); + + for (auto ch : text) { + + if (isalpha(ch) || isdigit(ch)) + text_.push_back(tolower(ch)); + } + + text_.shrink_to_fit(); + + size_ = ceil(sqrt(text_.size())); +} + +string cipher::normalize_plain_text() const +{ + return text_; +} + +size_t cipher::size() const +{ + return size_; +} + +cipher::segments_t cipher::plain_text_segments() const +{ + segments_t result; + + const size_t s = size(); + + for (size_t i = 0; i < text_.size(); i += s) + result.push_back(text_.substr(i, s)); + + return result; +} + +string cipher::cipher_text() const +{ + string result; + result.reserve(text_.size()); + + const segments_t segments = plain_text_segments(); + + for (size_t col = 0; col < size(); ++col) { + + for (size_t row = 0; row < segments.size(); ++row) { + + const string &segment = segments[row]; + + if (col >= segment.size()) + continue; + + result += segment[col]; + } + } + + return result; +} + +string cipher::normalized_cipher_text() const +{ + string result; + + const string text = cipher_text(); + const size_t s = size(); + + for (size_t i = 0; i < text.size(); i += s) { + + result += i ? " " : ""; + result += text.substr(i, s); + } + + return result; +} + + +} diff --git a/cpp/crypto-square/crypto_square.h b/cpp/crypto-square/crypto_square.h new file mode 100644 index 0000000..eb44b1e --- /dev/null +++ b/cpp/crypto-square/crypto_square.h @@ -0,0 +1,29 @@ +#pragma once + +#define EXERCISM_RUN_ALL_TESTS + +#include +#include + +namespace crypto_square { + +class cipher +{ + std::string text_; + std::size_t size_; + +public: + + typedef std::vector segments_t; + + cipher(const std::string &text); + + std::string normalize_plain_text() const; + std::size_t size() const; + segments_t plain_text_segments() const; + std::string cipher_text() const; + std::string normalized_cipher_text() const; +}; + +} +