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

时间:2013-10-09 10:36:04

标签: java algorithm permutation dna-sequence hamming-distance

是否有算法通过给定数量的最大允许位置(最大不匹配,最大汉明距离)生成字符串(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
  {?}

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

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

还有其他更有效的approcahes / implementation吗?

1 个答案:

答案 0 :(得分: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万候选人(假设我的代码是正确的)。

以上代码在我的机器上通过不到一秒的时间(没有打印),但是不要指望任何发生器能够在合理的时间内产生比这更多的东西,因为简单来说太多的可能性。