Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Polybius Square Cipher ใน C++

ในปัญหานี้ เราได้รับสตริงและเราต้องหาการเข้ารหัสเป็นตัวเลขโดยใช้ Polybius Square Cipher

Polybius Square Cipher

เป็นตารางที่ใช้สำหรับการแปลงตัวอักษรเป็นตัวเลข ตารางสำหรับการเข้ารหัสภาษาอังกฤษเป็นตาราง 5x5 คือมี 25 ช่องสำหรับ 26 ตัวอักษรของพจนานุกรมภาษาอังกฤษ ตัวอักษร i และ j ถูกเก็บไว้ร่วมกันในช่องเดียว

ตารางต่อไปนี้แสดง Polybius square Cipher:

1 2 3 4 5
1 A B C D E
2 F G H I, J K
3 L M N O P
4 Q R S T U
5 V W X Y Z

ตัวอักษรในตารางสามารถสุ่มได้ ขนาดของตารางก็สามารถเปลี่ยนได้ตามจำนวนตัวอักษรของภาษา

มาดูตัวอย่างเพื่อเข้าใจปัญหา:

Input - Hello

Output - 2315313134

เพื่อแก้ปัญหานี้ เราจะสร้างโปรแกรมเพื่อรับแต่ละคู่ของตัวเลขแล้วตรวจสอบตัวอักษรที่สอดคล้องกัน

ตัวอย่าง

โปรแกรมแสดงการประกอบโซลูชันของเรา:

#include <cmath>
#include <iostream>
using namespace std;

void LetterToNumber(string str) {
    int R, C;
    for (int i = 0; str[i]; i++) {
        R = ceil((str[i] - 'a') / 5) + 1;
        C = ((str[i] - 'a') % 5) + 1;
        if (str[i] == 'k') {
            R = R - 1;
            C = 5 - C + 1;
        } else if (str[i] >= 'j') {
            if (C == 1) {
                C = 6;
                R = R - 1;
            }
            C = C - 1;
        }
        cout << R << C;
    }
    cout << endl;
}

int main() {
    string str = "tutorialspoint";
    cout << "The numeric encryption of string '" << str << "' is : ";
    LetterToNumber(str);
    return 0;
}

ผลลัพธ์

The numeric encryption of string 'tutorialspoint' is: 4445443442241131433534243344