Function Name: caesarShift Inputs: 1. (char) A string to be encoded 2. (double)
ID: 3749733 • Letter: F
Question
Function Name: caesarShift
Inputs:
1. (char) A string to be encoded
2. (double) The shift number
Outputs:
1. (char) An encoded string
Function Background: You're going to Music Midtown '18! 18 BCE that is, of course! You're a famous artist in Roman times. You want to send the lyrics to be edited, but you don't want the couriers to read it, so you decide to encrypt your lyrics. You remember that your friend, Julius Caesar, had a great method for encoding his messages. Caesar shifted each letter over 3 places, so that 'a' became 'd'. The shift wraps around the end of the alphabet, so the letter 'z' would shift to become the letter 'c'. However, the Caesar shift is relatively easy to crack today, so in order to encrypt all of the lyrics, you decide to make it harder to crack by adding some more steps. Being a Roman MATLAB pro, you decide to write a function that does it for you!
Function Description: The function takes in a string to be encoded and a shift number representing how far each letter will be shifted for the Caesar shifts you will perform. It then performs the following actions in order on the input string:
1. Convert all letters to uppercase, since classical Latin had one case.
2. For letters with even ASCII values, perform a Caesar shift using the given shift number.
3. For letters with odd ASCII values, perform a Caesar shift using the negative of the shift number.
4. Replace all instances of 'J' with 'I' and 'U' with 'V', since classical Latin had no J's or U's (Julius Caesar was written as IVLIVS CAESAR).
5. Concatenate the number of consonants in the resulting string with the output string, including the 'V's added in Step 4.
Notes:
The function should work for both positive and negative shift values of any magnitude.
Consonants are defined as letters that are not A, E, I, O, or U (and not spaces).
The input string is guaranteed to only consist of letters and spaces. Classical Latin did not use punctuation. Hints:
The mod() and strrep() and num2str() functions and will be useful.
Explanation / Answer
%caesarShift function
function [str_encoded] = caesarShift(str, shift)
spaces = find(str == 32);
str = upper(str);
even_odd = mod(str,2);
even_odd(spaces) = 32;
even = find(even_odd == 0);
odd = find(even_odd == 1);
str(even) = mod(str(even)+shift-64,26)+64;
str(odd) = mod(str(odd)-shift-64,26)+64;
str(str==64) = 90;
% this will replace all the instances of J with I
str(str=='J') = 'I';
% this will replace all the instances of U with V
str(str=='U') = 'V';
consonant = str(str~='A' & str~='E' & str~='I' & str~='O' & str~=32);
len = num2str(length(consonant));
str_encoded = [str len];
end
If you have any doubt please ask me friend and if you are satisfied with my solution please give me thumb up
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.