Bryan Smith
Bryan Smith

Reputation: 45

Decrypting a Caesar's Cypher Trouble

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

Answers (2)

Pradeep
Pradeep

Reputation: 1264

You can go like this.

  1. First read whole file in a buffer.
  2. Create map with char key and int value. with all alphabets and values 0
  3. Loop 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.

  4. At end of loop max variable will point to e.

  5. Subtracting 4 from 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

Sani Huttunen
Sani Huttunen

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

Related Questions