crypto_square: iteration 1

This commit is contained in:
Dmitry Kokorin 2016-04-07 23:29:13 +03:00
parent 5f232d2fe3
commit 76d5f8c99c
2 changed files with 116 additions and 0 deletions

View file

@ -0,0 +1,87 @@
#include "crypto_square.h"
#include <algorithm>
#include <cmath>
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;
}
}