Today’s problem - Caesar Salad
A Caesar cipher, also known as a shift cipher, is one of the simplest encryption techniques. In a Caesar cipher, each letter in the plaintext is replaced by a letter some fixed number of positions away in the alphabet, effectively “shifting” the alphabet.
Write a function that:
takes a single integer left argument representing the size of the shift
takes a character vector right argument representing the plaintext message
returns a result with the same shape as the right argument representing the encrypted message
Notes:
Use ' ',⎕A as the alphabet
You can assume that the plaintext message will contain only characters found in the alphabet.
Hint: The rotate function ⌽ could be helpful in solving this problem.
Examples
4 caesar 'HELLO WORLDS'
LIPPSD SVPHW
¯4 caesar 'HELLO WORLDS' ⍝ negative shifts are okay
DAHHKWSKNH O
0 caesar 'HELLO WORLDS' ⍝ no shift is okay
HELLO WORLDS
27 caesar 'HELLO WORLDS'
HELLO WORLDS
¯10 caesar '' ⍝ returns an empty vector
Solution
See the solution
{(⍺⌽' ',⎕A)[(' ',⎕A) ⍸⍵]}
Breaking it down:
- 1. Define the alphabet:
' ',⎕Acreates our alphabet consisting of a space followed by the uppercase letters A-Z. - 2. Find positions in the alphabet:
(' ',⎕A) ⍸⍵uses the index-of (⍸) function to find the positions of each character in the input string (⍵) within our alphabet. - 3. Create the shifted alphabet:
⍺⌽' ',⎕Arotates our alphabet by the shift amount (⍺). The rotate function (⌽) shifts the entire alphabet by the specified number of positions. - 4. Map to the new characters: Using the positions found in step 2, we index into the shifted alphabet:
(⍺⌽' ',⎕A)[...]to get our encrypted message.