Uploaded by asadullosattarov10

Kriptografiya2 1amaliy ish

advertisement
951-21 guruh talabasi
Sattarov Asadullo
1-amaliy mashg’ulot
#include <iostream>
#include <string>
#include <cctype> // isalpha() funksiyasini ishlatish uchun
#include <unordered_map>
#include <algorithm> // std::max_element funksiyasini ishlatish uchun
std::pair<int, int> calculateMostFrequentIndex(const std::string& text) {
std::unordered_map<char, int> frequencies;
// Xarf sanini hisoblash
for (char ch : text) {
if (std::isalpha(ch)) {
frequencies[std::tolower(ch)]++;
}
}
// Eng ko'p qatnashgan xarfni topish
auto maxElement = std::max_element(frequencies.begin(), frequencies.end(),
[](const auto& a, const auto& b) {
return a.second < b.second; // Katta bo'lgan qiymatni
topish uchun
});
// Eng ko'p qatnashgan xarfning indeksini hisoblash
int mostFrequentIndex = maxElement->first - 'a' + 1; // Lotin alifbosi indeksi
// 'E' xarfining indeksini hisoblash
int eIndex = 'e' - 'a' + 1;
// Indeks va e xarfi indeksi farqini hisoblash
return std::make_pair(mostFrequentIndex, eIndex);
}
std::string decryptCaesarCipher(const std::string& ciphertext, int key) {
std::string decryptedText = "";
for (char ch : ciphertext) {
if (std::isalpha(ch)) {
char base = (std::isupper(ch)) ? 'A' : 'a';
decryptedText += static_cast<char>((ch - base + 26 - key) % 26 + base); //
26 qo'shib mod operatsiyasini 26 ga qilamiz
} else {
decryptedText += ch;
}
}
return decryptedText;
}
int main() {
std::string text;
// Matnni olish
std::cout << "Matnni kiriting: ";
std::getline(std::cin, text);
// Eng ko'p qatnashgan xarfni va 'E' xarfi o'rtasidagi farqni topish
std::pair<int, int> result = calculateMostFrequentIndex(text);
// Natijani chiqarish
std::cout << "Eng ko'p qatnashgan xarf Lotin alifbosida " << result.first << "inchi indeksda joylashgan, 'E' xarfi " << result.second << "-inchi indeksda
joylashgan. Modul: " << abs(result.first - result.second) << std::endl;
// Sezar shifrlash usulining kalitini aniqlash
int shiftKey = abs(result.first - result.second); // Sezar shifri kaliti
// Matnni deshifrlash
std::string decryptedText = decryptCaesarCipher(text, shiftKey);
// Natijani chiqarish
std::cout << "Chiqqan sonning moduli Sezar shifrlash usulining kaliti: " <<
shiftKey << std::endl;
std::cout << "Deshifrlovchi matn: " << decryptedText << std::endl;
return 0;
}
Download