【问题标题】:Caesar Cipher Frequency Analysis in JavaJava中的凯撒密码频率分析
【发布时间】:2018-11-22 15:10:33
【问题描述】:

Caesar Cipher using Frequency Analysis** in Java:这是我的解码部分代码:

public static String decode (String code){
    int key=0;
    final int ALPHABET_SIZE = 26;
    int[] freqs = new int[ALPHABET_SIZE];
    for (int l=0;l<freqs.length;l++){ 
        freqs[l]=0;
    }
    for (int k=0;k<code.length();k++){
        if (code.charAt(k)>='a' && code.charAt(k)<='z'){
            freqs[code.charAt(k)-'a']++;
        }
    }
    int biggest = 0;
    for (int t=0;t<freqs.length;t++){
        if (freqs[t]>biggest){
            biggest= t;
        }
    }
    if (biggest<4){
        key = (biggest + 26 - ('e'+'a'));

    }
    else{
        key = biggest + 'a' - 'e';
    }
    return (decode(code,key));
}

我不能使用映射、导入、列表或添加键,我知道频率最高的字母是 E,但我不知道如何在不同的函数中实现它。我将不胜感激一个更优雅的解决方案,谢谢。 ** 频率分析

【问题讨论】:

  • 更优雅的解决方案将使用您拥有的所有 Java 对象它是一种面向对象语言,因此更好的解决方案将使用它
  • 字母频率:ETAOINSHRDLU...虽然[空格]比E更频繁。

标签: java caesar-cipher frequency-analysis


【解决方案1】:

我不太确定您对“优雅”的定义是什么,但您的解决方案总体上看起来不错。

几个cmets:

  1. 您实际上不必在开始时手动将数组初始化为 0,因为 Java 会为您完成这项工作

  2. 可以在计算字符的同时查找频率最高的字母

例如,for 循环可以变成:

int highestFreq = 0;
int highestFreqIdx = -1;
for (int k=0; k < code.length(); k++) {
    if (code.charAt(k) >= 'a' && code.charAt(k) <= 'z') {
        int count = freqs[code.charAt(k)-'a']++;

        if (count > highestFreq) {
          highestFreq = count;
          highestFreqIdx = k;
        }
    }
}
  1. 可以简化密钥的计算

如果我没记错的话,你的关键是频率最高的字母远离'e'的位置数。在这种情况下,您可以简单地这样做:

key = biggest - ('e' - 'a');

所以你的代码变成了:

public static String decode (String code){
    int key = 0;
    final int ALPHABET_SIZE = 26;
    int[] freqs = new int[ALPHABET_SIZE];

    int highestFreq = 0;
    int highestFreqIdx = -1;
    for (int k=0; k < code.length(); k++) {
        if (code.charAt(k) >= 'a' && code.charAt(k) <= 'z') {
            int count = freqs[code.charAt(k)-'a']++;

            if (count > highestFreq) {
              highestFreq = count;
              highestFreqIdx = k;
            }
        }
    }

    key = highestFreqIdx - ('e' - 'a'); // Can also directly use 4 instead of 'e' - 'a'

    return (decode(code, key));
}

也就是说,您的代码仅适用于真正以字母“e”作为最常见字母的消息...

P/S 这样的代码审查问题在this Stack Exchange site for code reviews instead 中可能会更好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多