I have been set a task to create an enigma machine in C++. I am currently stuck on a question that is as follows:
'Write a function that takes a string as input and returns true if this string is a permutation of the alphabet and false otherwise.'
The alphabet in this case is a string set to: "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,’ " (please exclude quotes)
I have written the following code which should return 1 if the inputted string is the same length as the alphabet, and if the string is a permutation. My code does not take into account the is_permutation and seems to return 0 regardless. I was wondering if I have missed something out or if there is a better way to approach this?
#include<iostream>
#include<string>
#include<iomanip>
#include<algorithm>
using namespace std;
int permutationCheck(string input) {
const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,’ ";
if (ALPHABET.length() == input.length()) {
bool flag[29] = { 0 };
if (is_permutation(ALPHABET.begin(), ALPHABET.end(), input.begin())) {
cout << "This is true" << endl;
return 1;
}
else {
return 0;
}
}
else {
return 0;
}
}
int main()
{string input;
cout << "Enter a permutation of the alphabet" << endl;
getline(cin, input);
cout << permutationCheck(input) << endl;
system("pause");
return 0;
}
Thanks for your reply, I have tested out the revised function, however I seem to get a 0 for all scenarios, even when the input is not a valid permutation.
I also seem to get a debug assertion error in Visual Studio when the length of the input does not match the alphabet string, is this normal?
Could you post your input? The code worked unmodified for me except for the input string.
If you add some trace to the else blocks, you'll have a better idea where things go wrong (see example below).
Anyhow your string ALPHABET may not be what you think. The next to last character that looks like the ASCII character for an apostrophe is actually the right quote unicode 209!
Have you opened the program in a debugger and looked at the values of input and ALPHABET to compare to each other? I'm guessing they actually aren't permutations but you think they are.
You are right, I had been thinking of the C++14 version of is_permutation() that allows the specification of a start and end for both strings used in the comparison. You can either use that one or re-add the length check you had before.
Thanks for your help. You were both right about the two strings not matching when I thought they were, the right quote(Unicode 209) was being mistaken for another character. This was made clear when the values were compared. The program is now working as expected