Relatively new to C++. I posted a previous question related to this before, and have since continued to work on the problem, to no avail.
Basically, I need a function that takes a string as input, then replaces the letters of the string based on another function.
This other function uses a string to define the characters that may be used in the input,
|
const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,' ";
|
then creates a permutation by randomly reorganising the letters.
1 2 3 4 5 6 7 8
|
string create_permutation(string permutation)
{
unsigned seed = chrono::system_clock::now().time_since_epoch().count();
shuffle(permutation.begin(), permutation.end(), default_random_engine(seed));
return permutation;
}
string permu = create_permutation(ALPHABET);
|
How do I essentially encrypt the message input, by looking up the alphabet letter, and then replacing the input letter with the corresponding permutation letter?
E.G.
Input is 'HELLO'
const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,' ";
permutation of ALPHABET = "BUYWPLJDKIXQSZGAVCEFN'MR,OT .H";
Output should be 'DPFFG' (D replaces H's place, P replaces E's place, etc)
Below is the full code used. Note that the inverse permutation would then be used to decrypt the encrypted message.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
#include <iostream>
#include <string>
#include <algorithm>
#include <random>
using namespace std;
const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,' ";
string create_permutation(string permutation)
{
cout << "Input seed" << endl;
unsigned seed;
cin >> seed;
shuffle(permutation.begin(), permutation.end(), default_random_engine(seed));
return permutation;
}
string findPermu2(const string& permu1)
{
string permu2(ALPHABET);
for (int i = 0; i<ALPHABET.length(); ++i)
for (int j = 0; j<ALPHABET.length(); ++j)
if (permu1[i] == ALPHABET[j])
{
permu2[j] = ALPHABET[i];
break;
}
return permu2;
}
int main()
{
string permu = create_permutation(ALPHABET);
string invpermu = findPermu2(permu);
cout << "Original ALPHABET: - " << ALPHABET << endl;
cout << "Permutation of ALPHABET: - " << permu << endl;
cout << "Inverse of Permutation: - " << invpermu << endl;
cout << endl << "Input any single character to begin" <<
endl << "Encryption / decryption, or '\Q'\ to [Q]uit" << endl;
char enterorquit;
cin >> enterorquit;
if (enterorquit == 'q' || enterorquit == 'Q')
{
return 0;
}
else
{
string inputmessage;
cout << "Type your message below" << endl;
cin >> inputmessage;
cout << endl << "Input \'E\' to [E]ncrypt, any other single character to decrypt:" << endl;
}
char encryptordecrypt;
if (encryptordecrypt == 'e' || encryptordecrypt == 'E')
{
cout << "Encrypted message: " << endl /*<< encrypted message here*/;
}
else
{
cout << "Decrypted message: " << endl /*<< decrypted message here*/;
}
return 0;
}
|