Programming Search⌘K

Taskintro

Apply a Caesar or ROT13 cipher

Also called Caesar cipher, Caesar shift, shift cipher, ROT13, rot-13, rot13 encode, rotate letters, letter rotation.

Move each letter a fixed number of places along the alphabet, from z back to a, and keep the case and all other characters. ROT13 is a shift of 13 and is its own inverse. The cipher gives no security.

Task

A Caesar cipher replaces each letter with a letter a fixed number of places along the alphabet. "The method is named after Julius Caesar, who used it in his private correspondence."1 The Rosetta Code task asks for "both encoding and decoding"2. Its example is that the key 2 changes HI to JK, and the key 20 changes HI to BC. The alphabet wraps, so the letter after Z is A.

ROT13 is the Caesar cipher with the shift 13. The Rosetta Code task explains that it "is commonly known from the early days of Usenet"3, where it hid spoilers and offensive text from a casual reader. Because the alphabet has 26 letters, "the ROT13 function is its own inverse"4: the same function encodes and decodes.

The function caesar(text, shift) moves each letter A to Z and a to z by shift places, from z back to a, and keeps its case. All other characters, such as digits, spaces, punctuation and letters outside ASCII, stay as they are. The shift can be any integer. A shift of 26 changes nothing, and a negative shift moves the letters back, so caesar(caesar(text, k), -k) is text.

The cipher is a puzzle, not a protection. As Wikipedia says, it "offers essentially no communications security"1. The Rosetta Code task notes that an attacker "can either use frequency analysis to guess the key, or just try all 25 keys"2.

Solutions

Each solution first reduces the shift to a number k from 0 to 25. Then a letter with the index i from 0 to 25 in its alphabet becomes the letter with the index (i + k) mod 26.

Language Shift from 0 to 25 Method
Python shift % 26 str.maketrans and str.translate
JavaScript, TypeScript ((shift % 26) + 26) % 26 replace(/[A-Za-z]/g, fn)
Java Math.floorMod(shift, 26) a loop over a char[]
C# ((shift % 26) + 26) % 26 string.Create with a loop
Go ((shift % 26) + 26) % 26 strings.Map
Rust shift.rem_euclid(26) chars().map(...).collect()
C ((shift % 26) + 26) % 26 a loop over the bytes
C++ ((shift % 26) + 26) % 26 std::ranges::transform
Bash (((shift % 26) + 26) % 26) tr with two rotated alphabets
  • The remainder. In most languages of this site, % gives a negative result for a negative left side. In JavaScript, the remainder "always takes the sign of the dividend"5, so -1 % 26 is -1. ((shift % 26) + 26) % 26 gives a value from 0 to 25 for each shift. Python's % already gives a result with the sign of the right side. Rust has rem_euclid, which "Calculates the least nonnegative remainder"6, and Java has Math.floorMod.
  • Python. str.maketrans "returns a translation table usable for str.translate()"7. The solution maps the alphabet to the alphabet rotated by k, for upper and lower case. For ROT13 only, codecs.encode(text, "rot13") works: the codec rot_13 is listed with the meaning "Return the Caesar-cypher encryption of the operand"8.
  • Go. strings.Map calls a function for each rune and builds a new string. A rune outside A to Z and a to z comes back unchanged.
  • C. The function changes the text in place. Each byte of a UTF-8 character outside ASCII is 0x80 or more, so it is not in a range of letters, and it stays as it is.
  • Bash. The tr utility copies its input "with substitution or deletion of selected characters"9. The solution builds the rotated alphabets with ${upper:k}${upper:0:k} and calls tr 'A-Za-z' with them. LC_ALL=C makes tr work on bytes, so the bytes of UTF-8 text outside ASCII are not changed.

Python, with a table and with the codec:

import codecs
import string


def caesar(text, shift):
    k = shift % 26
    lower, upper = string.ascii_lowercase, string.ascii_uppercase
    table = str.maketrans(lower + upper, lower[k:] + lower[:k] + upper[k:] + upper[:k])
    return text.translate(table)


secret = caesar("Hello, World!", 3)
print(secret, caesar(secret, -3))
print(caesar("HI", 2), caesar("HI", 20), -1 % 26)
print(codecs.encode("Hello, World!", "rot13"))
print(caesar(caesar("Uryyb", 13), 13))
Output
Khoor, Zruog! Hello, World!
JK BC 25
Uryyb, Jbeyq!
Uryyb

Edge cases

  • Empty text. The result is empty.
  • Shift 0 and shift 26. The text does not change.
  • Negative shift. caesar("abc", -1) is zab. A shift of -13 decodes ROT13, and so does a shift of 13.
  • A shift above 26. 27 is the same as 1, so caesar("xyz", 27) is yza.
  • The end of the alphabet. caesar("Zz", 1) is Aa, not [ and {, the characters after Z and z in ASCII.
  • Characters next to the letters. @ comes before A, and [, ` and { come next to the letters. They are not letters, so they stay as they are.
  • Letters outside ASCII. café ü with shift 1 becomes dbgé ü. The contract changes only A to Z and a to z.
  • A large shift. With the shift 2^53 - 1, which is 5 mod 26, abc becomes fgh. A program that adds the shift to the letter before it takes the remainder can overflow a 32-bit integer.

Pitfalls

  • A negative remainder. In JavaScript, Java, C#, Go, C and C++, % keeps the sign of the left side. A shift of -1 then gives an index of -1, and the program makes a character that is not a letter:

This code runs but gives a wrong answer on purpose.

function caesar(text, shift) {
  return text.replace(/[a-z]/g, (c) =>
    String.fromCharCode(((c.charCodeAt(0) - 97 + shift) % 26) + 97),
  );
}

console.log(caesar("abc", 1), caesar("abc", -1));
Output
bcd `ab

a became `, the character before a. Reduce the shift with ((shift % 26) + 26) % 26 first.

  • Only one case. A loop that tests only a to z leaves upper case letters unchanged. A loop that uses the base 'a' for upper case letters too gives wrong characters, because 'Z' - 'a' is negative.
  • Letters outside ASCII. str.isalpha in Python, Character.isLetter in Java and char.IsLetter in C# accept é. Then c - 'a' is not an index from 0 to 25. Test the ranges A to Z and a to z.
  • Security. A Caesar cipher or ROT13 hides text from a casual reader only. Never use it to protect a password or private data.

Code

The build runs the native tests of each language in a pinned toolchain.

caesar.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

import string


def caesar(text: str, shift: int) -> str:
    """Move each letter A to Z and a to z shift places along the alphabet,
    from z back to a. Other characters do not change. A negative shift
    decodes, and caesar(text, 13) is ROT13."""
    k = shift % 26
    lower, upper = string.ascii_lowercase, string.ascii_uppercase
    table = str.maketrans(lower + upper, lower[k:] + lower[:k] + upper[k:] + upper[:k])
    return text.translate(table)


if __name__ == "__main__":
    print(caesar("Hello, World!", 13))
test_caesar.py 29 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

import pytest

from caesar import caesar

CASES = [
    ("hi-2", "HI", 2, "JK"),
    ("hi-20", "HI", 20, "BC"),
    ("rot13", "Hello, World!", 13, "Uryyb, Jbeyq!"),
    ("empty", "", 3, ""),
    ("zero", "abc", 0, "abc"),
    ("full-turn", "abc", 26, "abc"),
    ("minus-one", "abc", -1, "zab"),
    ("decode", "Uryyb, Jbeyq!", -13, "Hello, World!"),
    ("above-26", "xyz", 27, "yza"),
    ("wrap", "Zz", 1, "Aa"),
    ("non-letters", "123 !? [`{@", 5, "123 !? [`{@"),
    ("non-ascii", "café ü", 1, "dbgé ü"),
    ("large", "abc", 9007199254740991, "fgh"),
    ("large-negative", "abc", -9007199254740991, "vwx"),
]


@pytest.mark.parametrize(("name", "text", "shift", "want"), CASES, ids=[c[0] for c in CASES])
def test_caesar(name, text, shift, want):
    assert caesar(text, shift) == want
    assert caesar(want, -shift) == text
caesar.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

#ifndef CAESAR_HPP
#define CAESAR_HPP

#include <algorithm>
#include <string>

// Moves each letter A to Z and a to z shift places along the alphabet, from
// z back to a. Other bytes do not change. A negative shift decodes, and
// caesar(text, 13) is ROT13.
inline std::string caesar(std::string text, long long shift) {
    const int k = static_cast<int>(((shift % 26) + 26) % 26);
    std::ranges::transform(text, text.begin(), [k](char c) {
        if (c >= 'A' && c <= 'Z') {
            return static_cast<char>('A' + (c - 'A' + k) % 26);
        }
        if (c >= 'a' && c <= 'z') {
            return static_cast<char>('a' + (c - 'a' + k) % 26);
        }
        return c;
    });
    return text;
}

#endif
test_caesar.cpp 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

#include <climits>
#include <cstdio>
#include <string>

#include "caesar.hpp"

namespace {

struct test_case {
    const char* name;
    const char* text;
    long long shift;
    const char* want;
};

const test_case cases[] = {
    {"hi-2", "HI", 2, "JK"},
    {"hi-20", "HI", 20, "BC"},
    {"rot13", "Hello, World!", 13, "Uryyb, Jbeyq!"},
    {"empty", "", 3, ""},
    {"zero", "abc", 0, "abc"},
    {"full-turn", "abc", 26, "abc"},
    {"minus-one", "abc", -1, "zab"},
    {"decode", "Uryyb, Jbeyq!", -13, "Hello, World!"},
    {"above-26", "xyz", 27, "yza"},
    {"wrap", "Zz", 1, "Aa"},
    {"non-letters", "123 !? [`{@", 5, "123 !? [`{@"},
    {"non-ascii", "café ü", 1, "dbgé ü"},
    {"large", "abc", 9007199254740991LL, "fgh"},
    {"large-negative", "abc", -9007199254740991LL, "vwx"},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const std::string got = caesar(c.text, c.shift);
        if (got != c.want || caesar(got, -c.shift) != c.text) {
            std::printf("FAIL %s: got \"%s\"\n", c.name, got.c_str());
            ++failures;
        }
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Caesar.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

/** The Caesar cipher and ROT13. */
public final class Caesar {
    private Caesar() {}

    /**
     * Moves each letter A to Z and a to z shift places along the alphabet,
     * from z back to a. Other characters do not change. A negative shift
     * decodes, and caesar(text, 13) is ROT13. Math.floorMod gives a value
     * from 0 to 25 also for a negative shift.
     */
    public static String caesar(String text, long shift) {
        int k = (int) Math.floorMod(shift, 26L);
        char[] chars = text.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c >= 'A' && c <= 'Z') {
                chars[i] = (char) ('A' + (c - 'A' + k) % 26);
            } else if (c >= 'a' && c <= 'z') {
                chars[i] = (char) ('a' + (c - 'a' + k) % 26);
            }
        }
        return new String(chars);
    }

    public static void main(String[] args) {
        System.out.println(caesar("Hello, World!", 13));
    }
}
CaesarTest.java 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class CaesarTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("hi-2", "HI", (long) 2, "JK"),
                Arguments.of("hi-20", "HI", (long) 20, "BC"),
                Arguments.of("rot13", "Hello, World!", (long) 13, "Uryyb, Jbeyq!"),
                Arguments.of("empty", "", (long) 3, ""),
                Arguments.of("zero", "abc", (long) 0, "abc"),
                Arguments.of("full-turn", "abc", (long) 26, "abc"),
                Arguments.of("minus-one", "abc", (long) -1, "zab"),
                Arguments.of("decode", "Uryyb, Jbeyq!", (long) -13, "Hello, World!"),
                Arguments.of("above-26", "xyz", (long) 27, "yza"),
                Arguments.of("wrap", "Zz", (long) 1, "Aa"),
                Arguments.of("non-letters", "123 !? [`{@", (long) 5, "123 !? [`{@"),
                Arguments.of("non-ascii", "café ü", (long) 1, "dbgé ü"),
                Arguments.of("large", "abc", 9007199254740991L, "fgh"),
                Arguments.of("large-negative", "abc", -9007199254740991L, "vwx")
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void caesar(String name, String text, long shift, String want) {
        assertEquals(want, Caesar.caesar(text, shift));
        assertEquals(text, Caesar.caesar(want, -shift));
    }
}
caesar.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

#include "caesar.h"

void caesar(char *text, long long shift) {
    // In C, % keeps the sign of the left side, so add 26 and take % again.
    int k = (int)(((shift % 26) + 26) % 26);
    for (char *p = text; *p != '\0'; p++) {
        if (*p >= 'A' && *p <= 'Z') {
            *p = (char)('A' + (*p - 'A' + k) % 26);
        } else if (*p >= 'a' && *p <= 'z') {
            *p = (char)('a' + (*p - 'a' + k) % 26);
        }
    }
}
caesar.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

#ifndef CAESAR_H
#define CAESAR_H

// Moves each letter A to Z and a to z of text shift places along the
// alphabet, from z back to a, in place. Other bytes do not change, so UTF-8
// text keeps its other characters. A negative shift decodes, and
// caesar(text, 13) is ROT13.
void caesar(char *text, long long shift);

#endif
test_caesar.c 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

#include "caesar.h"

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test_case {
    const char *name;
    const char *text;
    long long shift;
    const char *want;
};

static const struct test_case cases[] = {
    {"hi-2", "HI", 2, "JK"},
    {"hi-20", "HI", 20, "BC"},
    {"rot13", "Hello, World!", 13, "Uryyb, Jbeyq!"},
    {"empty", "", 3, ""},
    {"zero", "abc", 0, "abc"},
    {"full-turn", "abc", 26, "abc"},
    {"minus-one", "abc", -1, "zab"},
    {"decode", "Uryyb, Jbeyq!", -13, "Hello, World!"},
    {"above-26", "xyz", 27, "yza"},
    {"wrap", "Zz", 1, "Aa"},
    {"non-letters", "123 !? [`{@", 5, "123 !? [`{@"},
    {"non-ascii", "café ü", 1, "dbgé ü"},
    {"large", "abc", 9007199254740991LL, "fgh"},
    {"large-negative", "abc", -9007199254740991LL, "vwx"},
};

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        char buf[64];
        snprintf(buf, sizeof buf, "%s", c->text);
        caesar(buf, c->shift);
        if (strcmp(buf, c->want) != 0) {
            printf("FAIL %s: got \"%s\"\n", c->name, buf);
            failures++;
        }
        caesar(buf, -c->shift);
        if (strcmp(buf, c->text) != 0) {
            printf("FAIL %s decoded: got \"%s\"\n", c->name, buf);
            failures++;
        }
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Caesar.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

/// <summary>The Caesar cipher and ROT13.</summary>
public static class Caesar
{
    /// <summary>
    /// Moves each letter A to Z and a to z shift places along the alphabet,
    /// from z back to a. Other characters do not change. A negative shift
    /// decodes, and Encode(text, 13) is ROT13.
    /// </summary>
    public static string Encode(string text, long shift)
    {
        var k = (int)(((shift % 26) + 26) % 26);
        return string.Create(text.Length, (text, k), static (span, state) =>
        {
            for (var i = 0; i < span.Length; i++)
            {
                var c = state.text[i];
                span[i] = c switch
                {
                    >= 'A' and <= 'Z' => (char)('A' + ((c - 'A' + state.k) % 26)),
                    >= 'a' and <= 'z' => (char)('a' + ((c - 'a' + state.k) % 26)),
                    _ => c,
                };
            }
        });
    }
}
CaesarTests.cs 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

using Xunit;

public sealed class CaesarTests
{
    public static TheoryData<string, string, long, string> Cases => new()
    {
        { "hi-2", "HI", 2, "JK" },
        { "hi-20", "HI", 20, "BC" },
        { "rot13", "Hello, World!", 13, "Uryyb, Jbeyq!" },
        { "empty", "", 3, "" },
        { "zero", "abc", 0, "abc" },
        { "full-turn", "abc", 26, "abc" },
        { "minus-one", "abc", -1, "zab" },
        { "decode", "Uryyb, Jbeyq!", -13, "Hello, World!" },
        { "above-26", "xyz", 27, "yza" },
        { "wrap", "Zz", 1, "Aa" },
        { "non-letters", "123 !? [`{@", 5, "123 !? [`{@" },
        { "non-ascii", "café ü", 1, "dbgé ü" },
        { "large", "abc", 9007199254740991, "fgh" },
        { "large-negative", "abc", -9007199254740991, "vwx" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Encode(string name, string text, long shift, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Caesar.Encode(text, shift));
        Assert.Equal(text, Caesar.Encode(want, -shift));
    }
}
caesar.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

/**
 * Moves each letter A to Z and a to z shift places along the alphabet, from
 * z back to a. Other characters do not change. A negative shift decodes, and
 * caesar(text, 13) is ROT13.
 */
export function caesar(text, shift) {
  const k = ((shift % 26) + 26) % 26;
  return text.replace(/[A-Za-z]/g, (c) => {
    const base = c <= "Z" ? 65 : 97;
    return String.fromCharCode(((c.charCodeAt(0) - base + k) % 26) + base);
  });
}
caesar.test.js 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { caesar } from "./caesar.js";

const cases = [
  ["hi-2", "HI", 2, "JK"],
  ["hi-20", "HI", 20, "BC"],
  ["rot13", "Hello, World!", 13, "Uryyb, Jbeyq!"],
  ["empty", "", 3, ""],
  ["zero", "abc", 0, "abc"],
  ["full-turn", "abc", 26, "abc"],
  ["minus-one", "abc", -1, "zab"],
  ["decode", "Uryyb, Jbeyq!", -13, "Hello, World!"],
  ["above-26", "xyz", 27, "yza"],
  ["wrap", "Zz", 1, "Aa"],
  ["non-letters", "123 !? [`{@", 5, "123 !? [`{@"],
  ["non-ascii", "café ü", 1, "dbgé ü"],
  ["large", "abc", 9007199254740991, "fgh"],
  ["large-negative", "abc", -9007199254740991, "vwx"],
];

for (const [name, text, shift, want] of cases) {
  test(name, () => {
    assert.equal(caesar(text, shift), want);
    assert.equal(caesar(want, -shift), text);
  });
}
caesar.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

/**
 * Moves each letter A to Z and a to z shift places along the alphabet, from
 * z back to a. Other characters do not change. A negative shift decodes, and
 * caesar(text, 13) is ROT13.
 */
export function caesar(text: string, shift: number): string {
  const k = ((shift % 26) + 26) % 26;
  return text.replace(/[A-Za-z]/g, (c: string) => {
    const base = c <= "Z" ? 65 : 97;
    return String.fromCharCode(((c.charCodeAt(0) - base + k) % 26) + base);
  });
}
caesar.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { caesar } from "./caesar.ts";

const cases: [string, string, number, string][] = [
  ["hi-2", "HI", 2, "JK"],
  ["hi-20", "HI", 20, "BC"],
  ["rot13", "Hello, World!", 13, "Uryyb, Jbeyq!"],
  ["empty", "", 3, ""],
  ["zero", "abc", 0, "abc"],
  ["full-turn", "abc", 26, "abc"],
  ["minus-one", "abc", -1, "zab"],
  ["decode", "Uryyb, Jbeyq!", -13, "Hello, World!"],
  ["above-26", "xyz", 27, "yza"],
  ["wrap", "Zz", 1, "Aa"],
  ["non-letters", "123 !? [`{@", 5, "123 !? [`{@"],
  ["non-ascii", "café ü", 1, "dbgé ü"],
  ["large", "abc", 9007199254740991, "fgh"],
  ["large-negative", "abc", -9007199254740991, "vwx"],
];

for (const [name, text, shift, want] of cases) {
  test(name, () => {
    assert.equal(caesar(text, shift), want);
    assert.equal(caesar(want, -shift), text);
  });
}
caesar.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

// Package caesar holds the Caesar cipher and ROT13.
package caesar

import "strings"

// Caesar moves each letter A to Z and a to z shift places along the
// alphabet, from z back to a. Other characters do not change. A negative
// shift decodes, and Caesar(text, 13) is ROT13.
func Caesar(text string, shift int64) string {
	k := rune(((shift % 26) + 26) % 26)
	return strings.Map(func(r rune) rune {
		switch {
		case r >= 'A' && r <= 'Z':
			return 'A' + (r-'A'+k)%26
		case r >= 'a' && r <= 'z':
			return 'a' + (r-'a'+k)%26
		}
		return r
	}, text)
}
caesar_test.go 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

package caesar

import "testing"

var cases = []struct {
	name  string
	text  string
	shift int64
	want  string
}{
	{"hi-2", "HI", 2, "JK"},
	{"hi-20", "HI", 20, "BC"},
	{"rot13", "Hello, World!", 13, "Uryyb, Jbeyq!"},
	{"empty", "", 3, ""},
	{"zero", "abc", 0, "abc"},
	{"full-turn", "abc", 26, "abc"},
	{"minus-one", "abc", -1, "zab"},
	{"decode", "Uryyb, Jbeyq!", -13, "Hello, World!"},
	{"above-26", "xyz", 27, "yza"},
	{"wrap", "Zz", 1, "Aa"},
	{"non-letters", "123 !? [`{@", 5, "123 !? [`{@"},
	{"non-ascii", "café ü", 1, "dbgé ü"},
	{"large", "abc", 9007199254740991, "fgh"},
	{"large-negative", "abc", -9007199254740991, "vwx"},
}

func TestCaesar(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := Caesar(c.text, c.shift); got != c.want {
				t.Fatalf("Caesar(%q, %d) = %q, want %q", c.text, c.shift, got, c.want)
			}
			if got := Caesar(c.want, -c.shift); got != c.text {
				t.Fatalf("Caesar(%q, %d) = %q, want %q", c.want, -c.shift, got, c.text)
			}
		})
	}
}
caesar.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

/// Moves each letter A to Z and a to z `shift` places along the alphabet,
/// from z back to a. Other characters do not change. A negative shift
/// decodes, and `caesar(text, 13)` is ROT13.
pub fn caesar(text: &str, shift: i64) -> String {
    // rem_euclid gives a value from 0 to 25, also for a negative shift.
    let k = u8::try_from(shift.rem_euclid(26)).expect("0 to 25");
    text.chars()
        .map(|c| match c {
            'A'..='Z' => char::from(b'A' + (c as u8 - b'A' + k) % 26),
            'a'..='z' => char::from(b'a' + (c as u8 - b'a' + k) % 26),
            _ => c,
        })
        .collect()
}
tests/caesar_test.rs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

use algo_apply_a_caesar_or_rot13_cipher::caesar;

const CASES: &[(&str, &str, i64, &str)] = &[
    ("hi-2", "HI", 2, "JK"),
    ("hi-20", "HI", 20, "BC"),
    ("rot13", "Hello, World!", 13, "Uryyb, Jbeyq!"),
    ("empty", "", 3, ""),
    ("zero", "abc", 0, "abc"),
    ("full-turn", "abc", 26, "abc"),
    ("minus-one", "abc", -1, "zab"),
    ("decode", "Uryyb, Jbeyq!", -13, "Hello, World!"),
    ("above-26", "xyz", 27, "yza"),
    ("wrap", "Zz", 1, "Aa"),
    ("non-letters", "123 !? [`{@", 5, "123 !? [`{@"),
    ("non-ascii", "café ü", 1, "dbgé ü"),
    ("large", "abc", 9007199254740991, "fgh"),
    ("large-negative", "abc", -9007199254740991, "vwx"),
];

#[test]
fn cases() {
    for &(name, text, shift, want) in CASES {
        assert_eq!(caesar(text, shift), want, "{name}");
        assert_eq!(caesar(want, -shift), text, "{name} decoded");
    }
}
caesar.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

# caesar text shift: print text with each letter A to Z and a to z moved
# shift places along the alphabet, from z back to a. Other characters do not
# change. A negative shift decodes, and caesar text 13 is ROT13. tr maps the
# alphabet to the rotated alphabet. LC_ALL=C makes tr work on bytes, so the
# bytes of UTF-8 characters outside ASCII stay as they are.
caesar() {
  local upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ lower=abcdefghijklmnopqrstuvwxyz
  local k=$(((($2 % 26) + 26) % 26))
  printf '%s\n' "$1" | LC_ALL=C tr 'A-Za-z' "${upper:k}${upper:0:k}${lower:k}${lower:0:k}"
}
test_caesar.bats 91 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/apply-a-caesar-or-rot13-cipher/.

setup() {
  source "$BATS_TEST_DIRNAME/caesar.sh"
}

@test "hi-2" {
  run caesar 'HI' 2
  [ "$status" -eq 0 ]
  [ "$output" = 'JK' ]
}

@test "hi-20" {
  run caesar 'HI' 20
  [ "$status" -eq 0 ]
  [ "$output" = 'BC' ]
}

@test "rot13" {
  run caesar 'Hello, World!' 13
  [ "$status" -eq 0 ]
  [ "$output" = 'Uryyb, Jbeyq!' ]
}

@test "empty" {
  run caesar '' 3
  [ "$status" -eq 0 ]
  [ "$output" = '' ]
}

@test "zero" {
  run caesar 'abc' 0
  [ "$status" -eq 0 ]
  [ "$output" = 'abc' ]
}

@test "full-turn" {
  run caesar 'abc' 26
  [ "$status" -eq 0 ]
  [ "$output" = 'abc' ]
}

@test "minus-one" {
  run caesar 'abc' -1
  [ "$status" -eq 0 ]
  [ "$output" = 'zab' ]
}

@test "decode" {
  run caesar 'Uryyb, Jbeyq!' -13
  [ "$status" -eq 0 ]
  [ "$output" = 'Hello, World!' ]
}

@test "above-26" {
  run caesar 'xyz' 27
  [ "$status" -eq 0 ]
  [ "$output" = 'yza' ]
}

@test "wrap" {
  run caesar 'Zz' 1
  [ "$status" -eq 0 ]
  [ "$output" = 'Aa' ]
}

@test "non-letters" {
  run caesar '123 !? [`{@' 5
  [ "$status" -eq 0 ]
  [ "$output" = '123 !? [`{@' ]
}

@test "non-ascii" {
  run caesar 'café ü' 1
  [ "$status" -eq 0 ]
  [ "$output" = 'dbgé ü' ]
}

@test "large" {
  run caesar 'abc' 9007199254740991
  [ "$status" -eq 0 ]
  [ "$output" = 'fgh' ]
}

@test "large-negative" {
  run caesar 'abc' -9007199254740991
  [ "$status" -eq 0 ]
  [ "$output" = 'vwx' ]
}

References

  1. Caesar cipher, Wikipedia, Introduction
  2. Rosetta Code, Caesar cipher (task text, from acmeism/RosettaCodeData), task text
  3. Rosetta Code, Rot-13 (task text, from acmeism/RosettaCodeData), task text
  4. ROT13, Wikipedia, Description
  5. Remainder (%), MDN Web Docs, Description
  6. i64, The Rust Standard Library, rem_euclid
  7. Built-in Types, Python documentation, str.maketrans; str.translate
  8. codecs, Codec registry and base classes, Python documentation, Text Transforms (rot_13)
  9. tr, The Open Group Base Specifications Issue 8, Description; Operands

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source