Caesar Cipher

Write a method that takes in an integer ‘offset’ and a string. Produce a new string, where each letter is shifted by ‘offset’. You may assume that the string contains only lowercase letters and spaces.

When shifting “z” by three letters, wrap around to the front of the alphabet to produce the letter “c”.  You may want to use the % modulo operation to handle wrapping of “z” to the front of the alphabet.

You’ll want to use String’s ‘ord’ method and Integer’s ‘chr’ method.  ‘ord’ converts a letter to an ASCII number code. ‘chr’ converts an ASCII number code to a letter.

You may look at the ASCII printable characters chart:

Notice that the letter ‘a’ has code 97, ‘b’ has code 98, etc., up to ‘z’ having code 122.

The solution, annotated by me:

Screen Shot 2016-08-23 at 3.57.00 PM

How the code works, in an example:

Screen Shot 2016-08-23 at 3.43.10 PM

Second time solving this problem, it seemed to make less sense to me..  I couldn’t solve it on my own AND it took me quite a bit to decipher the solution.

Anyways, here’s the thought process:

1. Split string into array of words

2. Write two while loops, first one to iterate through each word in the string, and second one to iterate through each letter in each word.

3. In the while loop for each letter, determine the location of each character by subtracting its ASCII value by 97 (which is “a”).

4. Determine where its new location should be by adding the offset value to its current location.  Use % 26 to account for wrapping “y” and “z” to the front of the alphabet.

5. Set the current letter to its new ASCII character determined  by the new location/index, and convert it to regular alphabet letter.

Example: (3, “abc xyz”) => “def abc”

(The following notes show the work for letter z.)


*If we didn’t use % 26, the new index for “z” would have been 28 which is more than the number of letters in the alphabet. 

Caesar Cipher

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s