maple实现移位算法

代码:

restart;

# ==============================================
# 自定义函数:判断字符是否为大写字母
# 输入:单个字符
# 返回:true(是大写字母)/false(不是)
# ==============================================
IsUpper := proc(char)
    member(char, {"A","B","C","D","E","F","G","H","I","J","K","L","M",
                  "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"});
end proc:

# ==============================================
# 自定义函数:判断字符是否为小写字母
# 输入:单个字符
# 返回:true(是小写字母)/false(不是)
# ==============================================
IsLower := proc(char)
    member(char, {"a","b","c","d","e","f","g","h","i","j","k","l","m",
                  "n","o","p","q","r","s","t","u","v","w","x","y","z"});
end proc:

# ==============================================
# 移位加密函数
# 输入:
#   plaintext - 要加密的字符串
#   shift - 移位的位数(整数)
# 返回:加密后的字符串
# ==============================================
ShiftEncrypt := proc(plaintext::string, shift::integer)
local i, char, encrypted, code, ascii;
    encrypted := "";  # 初始化加密结果为空字符串
    
    # 遍历明文的每个字符
    for i from 1 to length(plaintext) do
        char := substring(plaintext, i..i);  # 获取第i个字符
        
        # 将字符转换为ASCII码(返回的是列表,取第一个元素)
        ascii := convert(char, 'bytes')[1];
        
        if IsUpper(char) then
            # 处理大写字母:
            # 1. 计算字母在字母表中的位置(A=0, B=1,...)
            # 2. 应用移位并取模26(确保结果在0-25范围内)
            # 3. 转换回ASCII码并生成字符
            code := (ascii - 65 + shift) mod 26;
            encrypted := cat(encrypted, convert([65 + code], 'bytes'));
            
        elif IsLower(char) then
            # 处理小写字母(逻辑同上,使用小写字母的ASCII码97)
            code := (ascii - 97 + shift) mod 26;
            encrypted := cat(encrypted, convert([97 + code], 'bytes'));
            
        else
            # 非字母字符直接保留
            encrypted := cat(encrypted, char);
        end if;
    end do;
    
    return encrypted;  # 返回加密结果
end proc:

# ==============================================
# 测试加密解密过程
# ==============================================
plaintext := "Hello, Maple!";  # 测试明文
shift := 3;                   # 移位量

# 加密过程
ciphertext := ShiftEncrypt(plaintext, shift);

# 解密过程(使用负的移位量)
decrypted := ShiftEncrypt(ciphertext, -shift);

# 打印结果
printf("明文: %s\n", plaintext);
printf("加密后(shift=%d): %s\n", shift, ciphertext);
printf("解密后: %s\n", decrypted);

代码执行流程说明:

  1. 字符判断

    • IsUpper 检查字符是否在 A-Z 集合中

    • IsLower 检查字符是否在 a-z 集合中

  2. 加密过程

    • 'H' (72) → (72-65+3)%26=5 → 65+5=70 → 'K'

    • 'e' (101) → (101-97+3)%26=7 → 97+7=104 → 'h'

    • 非字母字符(如逗号、空格)保持不变

  3. 解密过程

    • 对密文再次应用加密函数,但使用负的移位量(-3)

    • 相当于逆操作,恢复原始字符

关键点说明:

  1. convert(char, 'bytes') 将字符转换为ASCII码列表(如 "A" → [65])

  2. convert([code], 'bytes') 将ASCII码转换回字符

  3. 模运算 (mod 26) 确保字母表循环(如 Z + 3 → C)

  4. cat() 函数用于字符串拼接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值