【问题标题】:Getting all string combinations by given maximal Hamming distance (number of mismatches) in Java通过Java中给定的最大汉明距离(不匹配的数量)获取所有字符串组合
【发布时间】:2013-10-09 10:36:03
【问题描述】:

是否有一种算法可以通过给定的最大允许位置数(最大不匹配、最大汉明距离)生成字符串(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 的最大汉明距离。

还有其他更有效的方法/实现吗?

【问题讨论】:

  • 递归调用为返回的所有值生成距离 1 组合并放入 Set 以避免重复的函数
  • 谢谢,我也试试那种解决办法。

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


【解决方案1】:

只需使用正常的排列生成算法,除了你绕过距离,当你有不同的字符时减少它。

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 万个候选者(假设我的代码是正确的)。

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

【讨论】:

  • 谢谢,这似乎工作得很好,除非 println() 很慢 :)
猜你喜欢
  • 1970-01-01
  • 2017-04-14
  • 2014-08-28
  • 2021-04-22
  • 2014-01-28
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
  • 2015-07-21
相关资源
最近更新 更多