Hi, I'm new to c++ and I'm not very good with it, but I've been asked to write a function that takes a string as input and returns true if this string is a permutation of the alphabet and false other wise.
Now I was provided with a function for the generation for a random permutation but I don't if it works or how to get it to work.
What I was given was:
for the alphabet and this for the generation of a random permutation
string create_permutation(unsigned seed)
{
srand(seed);
string permutation = ALPHABET;
// using built-in random generator:
random_shuffle(permutation.begin(), permutation.end());
return permutation;
}
I put all that in with the <iostream> header and the <algorithm> header and it didn't work .
Do I need other headers or do I need to change something in the function, or is it just that it won't work without the actual test as well?
I'm sorry for any rambling, this has just got me really stuck.
Thank you that is great and has helped me with some other functions. However how would I make it so that an inputted string of characters, checked and would come out as true if it is a permutation of the given alphabet and false if not. I'm sorry if this is really basic stuff.
In case using a canned method spoils the exercise...
is std::string str; a permutation of ALPHABET ?
It's easy.
Checklist: if( str.length() != 26 ) returnfalse;// wrong # of letters
If every letter is in the range 'A' to 'Z' and appears only once then str is a permutation of ALPHABET.
1 2 3 4 5 6
for( char c : str )// for each char in str
{
if( c < 'A' || c > 'Z' ) returnfalse;// illegal character found
if (c has been found already ) returnfalse;
}
returntrue;// all tests passed
I'll leave 'c has been found already' to you.
My method involves an array of 26 bools.
Yes, but what's the best we can get from an STL sort routine? O(n)log(n) ?
It's a small point, especially because n is so small (26), but it's a point because my algorithm is O(n) all day long, tyvm!
The canned (presumably optimized) solution is at most O(n*n) and at least O(n) (except for length mismatch case that is O(1) ), so yours might not last all day after all?