In: Computer Science
C. Design a RandomCipher class as a subclass of the substitutionCipher from exercise P-3.40, so that each instance of the class relies on a random permutation of letters for its mapping.
#include <iostream>
#include <string>
#include <ctime>
#include <stdlib.h>
#include <vector>
using namespace std;
class SubstitutionCipher
{
public:
//Define your key which is a permutation of 26 alphabets
string key;
SubstitutionCipher()
{
}
//Constructor to create an instance which initializes the key with the given permutation
SubstitutionCipher(string k)
{
key = k;
}
//function to encode a string
string encode(string data)
{
//initialize encoded data
string encodedData = data;
//replace each character in encodedData with the corresponding mapped data in key. We subtract a char with 'A' to get its position
for (int i = 0; i < data.length(); i++)
encodedData[i] = key.at(data.at(i) - 'A');
//return the encoded data
return encodedData;
}
//function to decode a string
string decode(string data)
{
//initialize decoded data
string decodedData = data;
//replace each character in decodedData with the corresponding reverse mapped data in key. We add the position with 'A' to get the corresponding char
for (int i = 0; i < data.length(); i++)
decodedData[i] = key.find(data.at(i)) + 'A';
//return the decoded data
return decodedData;
}
};
//RandomCipher is a subclass of SubstitutionCipher which initializes the key with random permutation
class RandomCipher : public SubstitutionCipher
{
public:
RandomCipher()
{
key = getRandomKey();
}
string getRandomKey()
{
int m = 26;
srand(time(NULL));
bool repeat = false;
string key = "abcdefghijklmnopqrstuvwxyz";
char letter;
for (int i = 0; i < m; i++)
{
do
{
repeat = false;
letter = rand() % 26 + 65; // generate new random number
for (int j = 0; j <= i; j++) // iterate through the already generated numbers
{
if (letter == key[j])
{ // if the generated number already exists, do the while again
repeat = true;
break;
}
}
} while (repeat);
key[i] = letter; // assign the unique number
repeat = false;
}
return key;
}
};
int main()
{
RandomCipher cipher;
string data = "DEBAJYOTI";
string encodedData = cipher.encode(data);
cout << data << " encoded as " << encodedData << endl;
string decodedData = cipher.decode(encodedData);
cout << encodedData << " decoded as " << decodedData;
}
//SAMPLE OUTPUT:
PLEASE LIKE IT RAISE YOUR THUMBS UP
IF YOU ARE HAVING ANY DOUBT FEEL FREE TO ASK IN COMMENT
SECTION