摩斯密码Java/Python实现

摩斯密码Java/Python实现


前言

摘自《犯罪大师》谜题关卡

在这里插入图片描述

一、Java实现

伪代码如下:

package com.hjc.demo.logic.morsecode;

import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Classname MorseCode
 * @Description TODO
 * @Date 2021/7/24 9:25
 * @Created by Mr.He
 * TODO 摩斯密码
 */
public class MorseCode {
   
    final int ZERO = 0;
    final int ONE = 1;

    public String transform(String[] value, int dense) {
   
        AtomicReference<String> result = new AtomicReference<>("");
        int j = 0;
        for (String s :
                value) {
   
            if (Objects.equals(dense, ZERO)) {
   
                if (!morseCodeTable().containsKey(s)) {
   
                    return null;
                }
                j = 0;
            }
            if (Objects.equals(dense, ONE)) {
   
                if (!morseCodeTable().containsValue(s)) {
   
                    return null;
                }
                j = 1;
            }

            int finalJ = j;
            morseCodeTable().forEach((k, v) -> {
   
                if(Objects.equals(finalJ,ZERO)){
   
                    if (Objects.equals(k, s.toUpperCase())) {
   
                        result.updateAndGet(v1 -
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
摩斯密码是一种将字母和数字转换成一系列点和划的编码方式,可以通过Python编程实现。下面是一个简单的实现方式: ```python # 定义摩斯密码字典 MORSE_CODE_DICT = { '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':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----' } def encrypt(message): cipher = '' for letter in message: if letter != ' ': cipher += MORSE_CODE_DICT[letter.upper()] + ' ' else: cipher += ' ' return cipher def decrypt(message): message += ' ' decipher = '' citext = '' for letter in message: if (letter != ' '): i = 0 citext += letter else: i += 1 if i == 2: decipher += ' ' else: decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT.values()).index(citext)] citext = '' return decipher # 示例 message = "CSDN AI助手" result = encrypt(message) print(result) result2 = decrypt(result) print(result2) ``` 该程序中,我们定义了一个摩斯密码字典 `MORSE_CODE_DICT`,其中包含了每个字母和数字对应的摩斯密码。`encrypt()` 函数接受一个字符串作为参数,返回该字符串的摩斯密码形式。`decrypt()` 函数接受一个摩斯密码形式的字符串作为参数,返回该字符串的明文形式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值