How to implement the ROT13 algorithm (replace a letter with the 13th letter after it) in Kotlin

1 Answer

0 votes
/*
ROT13 is a simple substitution cipher that replaces a letter with the 13th letter 
after it in the alphabet. Because the English alphabet has 26 letters (13 * 2), 
applying ROT13 twice restores the original text (it is its own inverse).
*/

/**
 * Applies the ROT13 cipher to the given string.
 *
 * ROT13 rotates each letter by 13 positions in the alphabet:
 * A <-> N, B <-> O, ..., M <-> Z
 * a <-> n, b <-> o, ..., m <-> z
 *
 * Non-alphabetic characters are left unchanged.
 * Applying ROT13 twice returns the original text.
 *
 * @param input The text to encode or decode.
 * @return The ROT13-transformed string.
 */
fun rot13(input: String): String =
    input
        .map { c ->
            when (c) {
                in 'A'..'Z' ->
                    ('A'.code + (c.code - 'A'.code + 13) % 26).toChar()

                in 'a'..'z' ->
                    ('a'.code + (c.code - 'a'.code + 13) % 26).toChar()

                else ->
                    // Leave digits, spaces, punctuation, etc. unchanged.
                    c
            }
        }
        .joinToString(separator = "")

fun main() {
    val input = "Hello, World! 123"

    val encoded = rot13(input)
    val decoded = rot13(encoded)

    println("Input   : $input")
    println("Encoded : $encoded")
    println("Decoded : $decoded")
}


/*
run:

Input   : Hello, World! 123
Encoded : Uryyb, Jbeyq! 123
Decoded : Hello, World! 123

*/

 



answered 2 days ago by avibootz

Related questions

...