gpt4 book ai didi

java - 在 Java 中通过给定的最大汉明距离(不匹配数)获取所有字符串组合

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:13:45 28 4
gpt4 key购买 nike

是否有一种算法可以通过给定数量的可以变化的最大允许位置(最大不匹配、最大汉明距离)生成一个字符串(DNA 序列)的所有可能的字符串组合?

字母表是{A,C,T,G}。

字符串 AGCC 和最大不匹配数 2 的示例:

Hamming distance is 0
{AGCC}
Hamming distance is 1
{CGCC, TGCC, GGCC, AACC, ACCC, ATCC, AGAC, AGTC, ..., AGCG}
Hamming distance is 2
{?}

一种可能的方法是生成一个包含给定字符串的所有排列的集合,迭代它们并删除所有具有更大汉明距离的字符串。

对于给定的 20 个字符的字符串和 5 的最大汉明距离,这种方法非常耗费资源。

是否有其他更有效的方法/实现?

最佳答案

只需使用普通的排列生成算法,只是绕过距离,在获得不同字符时递减它。

static void permute(char[] arr, int pos, int distance, char[] candidates)
{
if (pos == arr.length)
{
System.out.println(new String(arr));
return;
}
// distance > 0 means we can change the current character,
// so go through the candidates
if (distance > 0)
{
char temp = arr[pos];
for (int i = 0; i < candidates.length; i++)
{
arr[pos] = candidates[i];
int distanceOffset = 0;
// different character, thus decrement distance
if (temp != arr[pos])
distanceOffset = -1;
permute(arr, pos+1, distance + distanceOffset, candidates);
}
arr[pos] = temp;
}
// otherwise just stick to the same character
else
permute(arr, pos+1, distance, candidates);
}

调用:

permute("AGCC".toCharArray(), 0, 1, "ACTG".toCharArray());

性能说明:

对于长度为 20、距离为 5 和 5 个字符的字母表,已经有超过 1700 万个候选者(假设我的代码是正确的)。

上面的代码在我的机器上用了不到一秒钟的时间(没有打印),但是不要指望任何生成器能够在合理的时间内生成比这更多的东西,因为太多的可能性。

关于java - 在 Java 中通过给定的最大汉明距离(不匹配数)获取所有字符串组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19269654/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com