【问题标题】:Is there a way to calculate the hamming distance between a constant string and strings in a txt file?有没有办法计算 txt 文件中的常量字符串和字符串之间的汉明距离?
【发布时间】:2021-03-20 09:58:31
【问题描述】:

我需要计算一个常量字符串和一个包含其他字符串的 txt 文件之间的汉明距离,每个字符串在文件中各自的行中。然后将所有与常量距离相同的字符串放入一个ArrayList中?例如:汉明距离为 2 的所有字符串都在一个列表中,距离为 3 的所有字符串都在另一个列表中,等等)。

我知道如何计算 2 个字符串之间的汉明距离,但不是一个常数和 txt 文件中的 50 多个其他字符串。

任何帮助都会很棒,我是编程新手,所以谢谢!

作为我的第一步,我已将整个 txt 文件读入 ArrayList。

【问题讨论】:

    标签: java string arraylist hamming-distance


    【解决方案1】:

    我假设所有字符串都具有相同的大小。您可以使用 HashMap 来跟踪当前存在的汉明距离,键是汉明距离,val 是它们在 List 结果中的索引。

    public static int hammingDistance(String str1, String str2) {
        int index = 0, count = 0;
        while (index < str1.length()) {
            if (str1.charAt(index) != str2.charAt(index)) {
                count++;
            }
            index++;
        }
        return count;
    }
    
    public static List<List<String>> getHammingDistances(String constantString, List<String> strs) {
        List<List<String>> result = new ArrayList();
        HashMap<Integer, Integer> sizes = new HashMap();
        for (String str : strs) {
            int distance = hammingDistance(constantString, str);
            if (!sizes.containsKey(distance)) {
                sizes.put(distance, result.size());
                List<String> newDistances = new ArrayList();
                newDistances.add(str);
                result.add(new ArrayList(newDistances));
            } else {
                result.get(sizes.get(distance)).add(str);
            }
        }
        return result;
    }
    
    public static void main(String[] args){
        List<String> strs = new ArrayList<>();
        strs.add("abcde");
        strs.add("abcdf");
        strs.add("bbcde");
        strs.add("bcdef");
        List<List<String>> result = getHammingDistances("abcde", strs);
        System.out.println(result.toString());
    }
    

    【讨论】:

    • 如果我想使用 JavaFX 实现这个,字符串常量是 ComboBox 的选定值,这种方法是否可以实现(有一些变化)。
    • JavaFX 也支持 Java ArrayList 和 HashMap,没有太大区别,只需要注意输入输出的格式和类型即可。我想你知道如何设计 JavaFX、ComboBox 等。
    猜你喜欢
    • 2014-01-28
    • 1970-01-01
    • 2017-08-20
    • 2019-06-07
    • 2017-05-18
    • 2013-07-28
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    相关资源
    最近更新 更多