Skip to content

Rotational Cipher

Shift every Latin letter of a text a number of places along the alphabet, keeping its case and everything else.

Adapted from Exercism’s problem specification (MIT). Listed under Encoding & Ciphers.

// FILE: rotational_cipher.nomi
//# The rotational (Caesar) cipher over the Latin alphabet.

/// `text` with every Latin letter moved `key` places along the alphabet,
/// wrapping from `z` to `a` and keeping its case. Everything else is kept.
pub fn rotate(text: String, key: Int) -> String
    cipher = Map.merge(shifted('a'..='z', key), shifted('A'..='Z', key))

    text
    |> String.to_codepoints()
    |> Iter.map(fn letter -> Map.get(cipher, letter) |> Maybe.with_default(letter))
    |> Iter.to_list()
    |> String.from_codepoints()
end

/// Maps each letter of `alphabet` to the letter `key` places after it.
fn shifted(alphabet: Range<Codepoint>, key: Int) -> Map<Codepoint, Codepoint>
    rotated = alphabet |> Iter.cycle() |> Iter.drop(Int.modulo(key, 26))
    Iter.zip(alphabet, rotated) |> Iter.to_map()
end

// FILE: rotational_cipher_test.nomi
import rotational_cipher

test "rotate"
    [
        ("rotate a by 0, same output as input", "a", 0, "a"),
        ("rotate a by 1", "a", 1, "b"),
        ("rotate a by 26, same output as input", "a", 26, "a"),
        ("rotate m by 13", "m", 13, "z"),
        ("rotate n by 13 with wrap around alphabet", "n", 13, "a"),
        ("rotate capital letters", "OMG", 5, "TRL"),
        ("rotate spaces", "O M G", 5, "T R L"),
        ("rotate numbers", "Testing 1 2 3 testing", 4, "Xiwxmrk 1 2 3 xiwxmrk"),
        ("rotate punctuation", "Let's eat, Grandma!", 21, "Gzo'n zvo, Bmviyhv!"),
        (
            "rotate all letters",
            "The quick brown fox jumps over the lazy dog.",
            13,
            "Gur dhvpx oebja sbk whzcf bire gur ynml qbt.",
        ),
    ]
    |> subtests (description, text, key, expected), description
        assert rotational_cipher.rotate(text, key) == expected
    end
end
  • The cipher is a Map<Codepoint, Codepoint> built once per call from the ranges 'a'..='z' and 'A'..='Z': each range zipped with itself cycled and dropped by the key. A character that is not a key, such as a space or a digit, maps to itself through Maybe.with_default.
  • The map avoids codepoint arithmetic, which would pick 'a' or 'A' by the letter’s case, take its offset modulo 26 and turn the sum back with Int.to_codepoint(...)!. The map needs none of that, and a character outside both alphabets needs no test of its own.
  • Int.modulo(key, 26) keeps the key in one turn of the alphabet, so a negative key would rotate backwards. The canonical keys are all from 0 to 26.
  • The text is read with String.to_codepoints, since the alphabet ranges are codepoints, and written back with String.from_codepoints. That takes a List, as to_codepoints gives one, so the lazy map ends in Iter.to_list().