Reputation: 45
I have been stumped on this for a long time and I was wondering if anyone can help me out. How could I write a program that would calculate the shift value of an encrypted Caesar's Cypher file in C++? My assignment is to take each lower case letter and calculate how many times each is used, then find the most frequent character. I know I can do that with a map of char and int. But then I would have to go back to that letter to change it to the letter 'e'. With maps there's no way to search back through values. I think the only way is a vector of vectors but I wouldn't know how to find the letter again with those either. Does anyone know a better way or how could I use vectors to accomplish this?
Upvotes: 0
Views: 257
Reputation: 1264
You can go like this.
char
key and int
value. with all alphabets and values 0Loop over whole buffer till end incrementing value in map by 1 for each character. Also maintain max
variable storing key ha of character having maximum value.
At end of loop max
variable will point to e.
max
will give you shift value for this cipher. If it comes negative then you can add 26. (As this calculation in in mod 26)Upvotes: 1
Reputation: 24385
All you need is a vector of size 26 (one for each character) where A has index 0 and Z has index 25.
Go through the ciphertext and in the vector increase the value for the specified character index.
When you've gone through all the ciphertext then go through the vector and check for the highest value. This is probably the character E.
Now you take the index and subtract with 4 (index of E).
This yields the shift value.
Let's say 20 has the highest count then your shift value is 16.
Upvotes: 1