str_rot13 / str_shuffle

str_rot13(string $string): string — str_shuffle(string $string): string

Classic miscellany: ROT13, the self-inverse Caesar shift (applying it twice restores the input), and string shuffling (per the PHP manual NOT cryptographically secure - global Mt19937, no injectable engine).

C C23

C23
/* rot13: the classic self-inverse shift; shuffle via Fisher-Yates on
   rand() - sequence is libc-specific, so only derived facts are asserted. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void rot13(char *s) { /* in-place, self-inverse */
    for (; *s; ++s) {
        if (*s >= 'a' && *s <= 'z') *s = (char)('a' + (*s - 'a' + 13) % 26);
        else if (*s >= 'A' && *s <= 'Z') *s = (char)('A' + (*s - 'A' + 13) % 26);
    }
}

int main(void) {
    char msg[32] = {0}; /* zero-initialized buffer */
    strcpy(msg, "Hello, World!");
    rot13(msg);
    printf("%s\n", msg);
    rot13(msg);
    printf("%s\n", msg); /* self-inverse: back to the original */

    /* seeded shuffle: length and multiset are the portable facts */
    char cards[7] = "abcdef"; /* zero-initialized tail */
    srand(7);
    for (int i = 6 - 1; i > 0; --i) { /* Fisher-Yates */
        int j = rand() % (i + 1);
        char t = cards[i]; cards[i] = cards[j]; cards[j] = t;
    }
    printf("%d\n", (int)strlen(cards));
    /* insertion sort restores the identity permutation */
    for (int i = 1; cards[i]; ++i) {
        char key = cards[i];
        int j = i - 1;
        while (j >= 0 && cards[j] > key) { cards[j + 1] = cards[j]; --j; }
        cards[j + 1] = key;
    }
    printf("%s\n", cards);
    return 0;
}
Output
Uryyb, Jbeyq!
Hello, World!
6
abcdef

C++ C++26

C++26
// rot13 via unsigned-char arithmetic; shuffle with a SEEDED engine
// (std::mt19937 - injectable, unlike PHP's global-only str_shuffle).
#include <algorithm>
#include <iostream>
#include <random>
#include <string>

static char rot13c(char c) { // self-inverse ASCII shift
    if (c >= 'a' && c <= 'z') return (char)('a' + (c - 'a' + 13) % 26);
    if (c >= 'A' && c <= 'Z') return (char)('A' + (c - 'A' + 13) % 26);
    return c;
}

int main() {
    std::string msg = "Hello, World!";
    std::transform(msg.begin(), msg.end(), msg.begin(), rot13c);
    std::cout << msg << "\n";
    std::transform(msg.begin(), msg.end(), msg.begin(), rot13c);
    std::cout << msg << "\n"; // self-inverse

    std::string cards = "abcdef";
    std::mt19937 rng(7); // seeded engine: the sequence is reproducible
    std::shuffle(cards.begin(), cards.end(), rng);
    std::cout << cards.size() << "\n";
    std::sort(cards.begin(), cards.end());
    std::cout << cards << "\n"; // permutation proof
}
Output
Uryyb, Jbeyq!
Hello, World!
6
abcdef

C# v11.0.100

v11.0.100
// rot13 by char arithmetic; shuffle with an INJECTED Random(7) - the
// sequence is reproducible (PHP's str_shuffle cannot be injected).
using System.Linq;

static char Rot13(char c) => c switch { // self-inverse ASCII shift
    >= 'a' and <= 'z' => (char)('a' + (c - 'a' + 13) % 26),
    >= 'A' and <= 'Z' => (char)('A' + (c - 'A' + 13) % 26),
    _ => c };

var msg = "Hello, World!";
msg = new string(msg.Select(Rot13).ToArray());
Console.WriteLine(msg);
msg = new string(msg.Select(Rot13).ToArray());
Console.WriteLine(msg); // self-inverse

var cards = "abcdef".ToList();
var rng = new Random(7); // injected seed: reproducible sequence
for (int i = cards.Count - 1; i > 0; --i) { // Fisher-Yates
    int j = rng.Next(i + 1);
    (cards[i], cards[j]) = (cards[j], cards[i]);
}
Console.WriteLine(cards.Count);
Console.WriteLine(string.Concat(cards.OrderBy(c => c))); // permutation proof
Output
Uryyb, Jbeyq!
Hello, World!
6
abcdef

Go v1.27.4

v1.27.4
// rot13 byte mapping; shuffle on an INJECTED rand.Rand source - the
// sequence is reproducible (PHP's str_shuffle cannot be injected).
package main

import (
	"fmt"
	"math/rand"
	"sort"
	"strings"
)

func rot13(s string) string { // self-inverse ASCII shift
	var b strings.Builder
	for _, c := range []byte(s) {
		if c >= 'a' && c <= 'z' { c = 'a' + (c-'a'+13)%26 }
		if c >= 'A' && c <= 'Z' { c = 'A' + (c-'A'+13)%26 }
		b.WriteByte(c)
	}
	return b.String()
}

func main() {
	msg := rot13("Hello, World!")
	fmt.Println(msg)
	fmt.Println(rot13(msg)) // self-inverse

	cards := strings.Split("abcdef", "")
	rng := rand.New(rand.NewSource(7)) // injected seed: reproducible
	rng.Shuffle(len(cards), func(i, j int) { cards[i], cards[j] = cards[j], cards[i] })
	fmt.Println(len(cards))
	sort.Strings(cards)
	fmt.Println(strings.Join(cards, "")) // permutation proof
}
Output
Uryyb, Jbeyq!
Hello, World!
6
abcdef

Java v27.0.1

v27.0.1
// rot13 by char arithmetic; Collections.shuffle with an INJECTED Random(7)
// - the sequence is reproducible (PHP's str_shuffle cannot be injected).
import java.util.*;

public class Main {
    static char rot13(char c) { // self-inverse ASCII shift
        if (c >= 'a' && c <= 'z') return (char)('a' + (c - 'a' + 13) % 26);
        if (c >= 'A' && c <= 'Z') return (char)('A' + (c - 'A' + 13) % 26);
        return c;
    }
    static String rot13(String s) {
        var b = new StringBuilder();
        for (char c : s.toCharArray()) b.append(rot13(c));
        return b.toString();
    }
    public static void main(String[] args) {
        String msg = rot13("Hello, World!");
        System.out.println(msg);
        System.out.println(rot13(msg)); // self-inverse

        List<String> cards = new ArrayList<>(Arrays.asList("abcdef".split("")));
        Collections.shuffle(cards, new Random(7)); // injected seed
        System.out.println(cards.size());
        Collections.sort(cards);
        System.out.println(String.join("", cards)); // permutation proof
    }
}
Output
Uryyb, Jbeyq!
Hello, World!
6
abcdef

JavaScript v26.13.1

v26.13.1
// rot13 by regex mapping; Fisher-Yates on Math.random - NOT seedable
// (no standard seeding API), so only derived facts are asserted.
function rot13(s) { // self-inverse ASCII shift
    return s.replace(/[a-z]/gi, (c) => {
        const base = c <= "Z" ? 65 : 97;
        return String.fromCharCode(base + ((c.charCodeAt(0) - base + 13) % 26));
    });
}
const msg = rot13("Hello, World!");
console.log(msg);
console.log(rot13(msg)); // self-inverse

const cards = "abcdef".split("");
for (let i = cards.length - 1; i > 0; --i) { // Fisher-Yates
    const j = Math.floor(Math.random() * (i + 1));
    [cards[i], cards[j]] = [cards[j], cards[i]];
}
console.log(cards.length);
console.log(cards.sort().join("")); // permutation proof
Output
Uryyb, Jbeyq!
Hello, World!
6
abcdef

PHP v8.6.0

v8.6.0
// str_rot13 - Caesar shift 13, SELF-INVERSE: applying it twice restores
// the input. str_shuffle - one permutation of the string; per the PHP
// manual it is NOT cryptographically secure (global Mt19937 state) and
// cannot be seeded - derive facts instead of asserting a permutation.
echo str_rot13("Hello, World!"), "\n";
echo str_rot13(str_rot13("round trip")), "\n";
$shuffled = str_shuffle("abcdef");
echo strlen($shuffled), "\n";
$sorted = str_split($shuffled);
sort($sorted);
echo implode("", $sorted), "\n"; // permutation proof: sorting restores "abcdef"
Output
Uryyb, Jbeyq!
round trip
6
abcdef

Python v3.15.2

v3.15.2
# codecs "rot13" is the direct twin; random is seedable, so a seeded
# shuffle reproduces (PHP's str_shuffle cannot be seeded at all).
import codecs
import random

print(codecs.encode("Hello, World!", "rot13"))
print(codecs.encode(codecs.encode("round trip", "rot13"), "rot13")) # self-inverse

cards = list("abcdef")
random.seed(7) # seeded: reproducible sequence
random.shuffle(cards)
print(len(cards))
print("".join(sorted(cards))) # permutation proof
Output
Uryyb, Jbeyq!
round trip
6
abcdef

Rust v1.99.1

v1.99.1
// rot13 by byte mapping; shuffle on a SEEDED xorshift - std has no RNG,
// so a tiny injectable engine demonstrates seed -> reproducible sequence.
struct Xorshift(u64); // minimal seeded engine
impl Xorshift {
    fn next(&mut self) -> u64 {
        let mut x = self.0;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.0 = x;
        x
    }
}

fn rot13(s: &str) -> String { // self-inverse ASCII shift
    s.bytes()
        .map(|c| match c {
            b'a'..=b'z' => b'a' + (c - b'a' + 13) % 26,
            b'A'..=b'Z' => b'A' + (c - b'A' + 13) % 26,
            other => other,
        })
        .map(|c| c as char)
        .collect()
}

fn main() {
    let msg = rot13("Hello, World!");
    println!("{}", msg);
    println!("{}", rot13(&msg)); // self-inverse

    let mut cards: Vec<char> = "abcdef".chars().collect();
    let mut rng = Xorshift(7); // injected seed: reproducible
    for i in (1..cards.len()).rev() { // Fisher-Yates
        let j = (rng.next() % (i as u64 + 1)) as usize;
        cards.swap(i, j);
    }
    println!("{}", cards.len());
    cards.sort();
    println!("{}", cards.into_iter().collect::<String>()); // permutation proof
}
Output
Uryyb, Jbeyq!
Hello, World!
6
abcdef

TypeScript v26.13.1

v26.13.1
// Same as JavaScript: rot13 mapping + unseedable Fisher-Yates, so only
// derived facts (length, sorted restoration) are asserted.
function rot13(s: string): string {
    return s.replace(/[a-z]/gi, (c: string) => {
        const base: number = c <= "Z" ? 65 : 97;
        return String.fromCharCode(base + ((c.charCodeAt(0) - base + 13) % 26));
    });
}
const msg: string = rot13("Hello, World!");
console.log(msg);
console.log(rot13(msg));
const cards: string[] = "abcdef".split("");
for (let i = cards.length - 1; i > 0; --i) {
    const j: number = Math.floor(Math.random() * (i + 1));
    [cards[i], cards[j]] = [cards[j], cards[i]];
}
console.log(cards.length);
console.log(cards.sort().join(""));
Output
Uryyb, Jbeyq!
Hello, World!
6
abcdef

Language differences

ROT13: the Caesar cipher with shift 13, self-inverse (rot13(rot13(x)) === x) because 13+13=26; it maps ASCII letters only, digits and symbols pass through; PHP has the builtin str_rot13, Python codecs.encode(s, "rot13"), everyone else hand-writes. str_shuffle: the task description’s "shuffle uses a CSPRNG" contradicts the manual - the PHP manual explicitly cautions that it "does not generate cryptographically secure values"; since 7.1 it draws from the global Mt19937 instance (shared with mt_rand/shuffle - after mt_srand the str_shuffle output is in fact reproducible - but the API accepts no seed argument and allows no engine injection); for cryptographic randomness use Random\Randomizer + Random\Engine\Secure (see the randomizer entry) or random_bytes/random_int; assertions use derived facts (length preserved + sorting restores the multiset), never a concrete permutation - the standard way to test random output deterministically. Language contrast: Java/C#/Go/Rust/C can all inject an engine (new Random(7) / rand.NewSource(7) / hand-seeded) for a reproducible sequence - exactly what PHP str_shuffle cannot do; JavaScript/TS Math.random shares PHP’s ailment: unseedable (no standard API), so only derived-fact assertions. Teaching anchor: the three rules of randomness testing - never test concrete sequences, test conserved quantities (length/multiset), and when reproducibility is needed inject an engine (availability per language as noted).