Polybius Square Cipher in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a string and we have to find its integer encryption using the Polybius Square Cipher.

Polybius Square Cipher

It is a table that is used for the conversion of letters into numbers. The table for English encryption is a 5X5 table i.e. contains 25 cells for 26 alphabets of an English dictionary. The letters i and j are kept together in a single cell.

The following table shows a Polybius square Cipher


12345
1ABCDE
2FGHI, JK
3LMNOP
4QRSTU
5VWXYZ

The letter of the tables can be randomized. Also, the size of the table can be changed based on the number of alphabets of the language.

Let’s take an example to understand the problem,

Input − Hello

Output − 2315313134

To solve this problem, we will create a program to take each pair of numbers and then check for the corresponding letter.

Example

Program to show the illustration of our solution −

 Live Demo

#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;
}

Output

The numeric encryption of string 'tutorialspoint' is: 4445443442241131433534243344
raja
Published on 17-Apr-2020 08:51:41
Advertisements