Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- char solve_matrix[5][5];
- string code_word = "WHEATSON";
- pair <int, int> pos[200];
- bool is_bad(char c) {
- return c == ' ' || c == 'J';
- }
- ///разбивает строку на двойки
- vector <string> parse_string (string s) {
- ///все буквы на большие и удаляет пробелы с J
- transform(s.begin(), s.end(), s.begin(), ::toupper);
- auto ptr = remove_if(s.begin(), s.end(), is_bad);
- s.resize(ptr - s.begin());
- ///правила из вики
- vector <string> parsed;
- for (int i = 0; i < s.length(); i += 2) {
- string n = s.substr(i, 2);
- if (n.size() == 1) {
- n += "X";
- parsed.push_back(n);
- continue;
- }
- if (n[0] == n[1]) {
- n[1] = 'X';
- i--;
- }
- parsed.push_back(n);
- }
- return parsed;
- }
- ///построение матрицы
- void init_matrix(string code_word) {
- transform(code_word.begin(), code_word.end(), code_word.begin(), ::toupper);
- vector <bool> is_used(26, false);
- int x = 0, y = 0;
- ///по всем буквам кодового и установка неповторяющихся
- for (auto c: code_word) {
- if (!is_used[c - 'A']) {
- is_used[c - 'A'] = true;
- solve_matrix[x][y] = c;
- y++;
- if (y == 5)
- x++, y = 0;
- }
- }
- ///добавление всех остальных в алфавитном порялке
- for (int c = 'A'; c <= 'Z'; c++) {
- if (is_bad(c))
- continue;
- if (!is_used[c - 'A']) {
- is_used[c - 'A'] = true;
- solve_matrix[x][y] = c;
- y++;
- if (y == 5)
- x++, y = 0;
- }
- }
- ///сохранили позиции символов
- for (int i = 0; i < 5; i++)
- for (int j = 0; j < 5; j++)
- pos[solve_matrix[i][j]] = make_pair(i, j);
- }
- ///сама шифровка
- string hide(vector <string> parsed) {
- string res = "";
- for (auto x: parsed) {
- cout << x << ' ';
- ///тут получили позиции символов
- pair <int, int> p1, p2;
- p1 = pos[x[0]];
- p2 = pos[x[1]];
- ///ну и опять правила из вики
- if (p1.first != p2.first && p1.second != p2.second) {
- res += solve_matrix[p1.first][p2.second];
- res += solve_matrix[p2.first][p1.second];
- }
- if (p1.first == p2.first) {
- res += (p1.second == 4? solve_matrix[p1.first][0] : solve_matrix[p1.first][p1.second + 1]);
- res += (p2.second == 4? solve_matrix[p2.first][0] : solve_matrix[p2.first][p2.second + 1]);
- }
- if (p1.second == p2.second) {
- res += (p1.first == 4? solve_matrix[0][p1.second] : solve_matrix[p1.first + 1][p1.second]);
- res += (p2.first == 4? solve_matrix[0][p2.second] : solve_matrix[p2.first + 1][p2.second]);
- }
- }
- cout << "\n";
- return res;
- }
- void solve() {
- ///построили матрицу, посмотрели на нее
- init_matrix(code_word);
- for (int i = 0; i < 5; i++) {
- for (int j = 0; j < 5; j++)
- cout << solve_matrix[i][j];
- cout << "\n";
- }
- ///взяли строку и зашифровали
- string input = "IDIOCY OFTEN LOOKS LIKE INTELLIGENCE";
- cout << hide(parse_string(input));
- }
- int main() {
- solve();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement