lab4

 #include <iostream>

#include <vector>

#include <unordered_set>

#include <iomanip>

#include <cctype>

using namespace std;

vector<vector<char>> buildMatrix(string key) {

unordered_set<char> seen;

string forma edKey, alpha = "abcdefghiklmnopqrstuvwxyz";

for (char c : key + alpha) {

c = (c == 'j' ? 'i' : tolower(c));

if (isalpha(c) && seen.insert(c).second) forma edKey += c;

}

vector<vector<char>> mat(5, vector<char>(5));

for (int i = 0; i < 25; ++i) mat[i / 5][i % 5] = forma edKey[i];

cout << "\nKey Matrix:\n";

for (auto& row : mat) { for (char c : row) cout << setw(2) << c << ' '; cout << endl; }

return mat;

}

pair<int, int> findPos(const vector<vector<char>>& mat, char c) {

if (c == 'j') c = 'i';

for (int i = 0; i < 5; ++i)

for (int j = 0; j < 5; ++j)

if (mat[i][j] == c) return {i, j};

return {-1, -1};

}

string prepareText(string txt) {

string res;

for (char c : txt) if (isalpha(c)) res += (c == 'j' ? 'i' : tolower(c));

for (size_t i = 0; i < res.size(); i += 2)

if (res[i] == res[i + 1]) res.insert(i + 1, "x");

return res.size() % 2 ? res + 'x' : res;

}

string processText(string txt, const vector<vector<char>>& mat, bool enc) {

string res;

for (size_t i = 0; i < txt.size(); i += 2) {

auto [r1, c1] = findPos(mat, txt[i]);

auto [r2, c2] = findPos(mat, txt[i + 1]);

if (r1 == r2) {

res += mat[r1][(c1 + (enc ? 1 : 4)) % 5];

res += mat[r2][(c2 + (enc ? 1 : 4)) % 5];

} else if (c1 == c2) {

res += mat[(r1 + (enc ? 1 : 4)) % 5][c1];

res += mat[(r2 + (enc ? 1 : 4)) % 5][c2];

} else {

res += mat[r1][c2];

res += mat[r2][c1];

}

}

return res;

}

string restoreFormat(const string& original, const string& plain) {

string res;

int j = 0;

for (char c : original)

res += isalpha(c) ? (isupper(c) ? toupper(plain[j++]) : plain[j++]) : c;

return res;

}

int main() {

string txt, key;

getline(cin, key);

vector<vector<char>> mat = buildMatrix(key);

cout << "Enter text: "; getline(cin, txt);

string enc = processText(prepareText(txt), mat, true);

string dec = restoreFormat(txt, processText(enc, mat, false));

cout << "\nEncrypted: " << enc << "\nDecrypted: " << dec << endl;

return 0;

Comments

Popular posts from this blog

lab1

lab8

lab9