从最终println中删除起始密码子

时间:2017-11-19 06:25:30

标签: java

我需要在起始密码子atg和三个末端密码子之一tga,taa和tag之间打印出所有内容。我一直试图解决这个问题几天,但我似乎无法找到一种方法从最后打印出的内容中删除起始密码子EX:如果你使用我的代码,它将打印出ATGAAA但我需要打印出只有AAA。

Object.prototype.forEach = function(operation){
    for(var k in this){
        operation(this[k],k,this)
    }
}

var obj = {x:0,y:0,z:1290}

obj.forEach(function(el, index) {
     console.log(el+" "+index);
});

1 个答案:

答案 0 :(得分:0)

错误发生在printAll()函数中。

public static void printAll(String dna){
    String dnaLow = dna.toLowerCase();
    int start = 0;
    while (true) {
        int loc = dnaLow.indexOf( "atg", start );

        int stop = findStopIndex( dnaLow, loc+3 );
        if ( stop != dna.length() ) {
            System.out.println( dna.substring(loc, stop) );
            start = stop + 3;
        } else {
            start = start + 3;
        }    
    }
}

这里的主要问题是你使用了太多的变量。您应该只需要start变量,而不是loc变量。如果我们切换所有出现的loc并摆脱丑陋的算术,函数将如下所示:

public static void printAll(String dna){
    String dnaLow = dna.toLowerCase();
    int start = 0;
    while (true) {
        start = dnaLow.indexOf( "atg", start ) + 3;
        int stop = findStopIndex( dnaLow, start );
        if ( stop != dna.length() ) {
            System.out.println( dna.substring(start, stop) );
            start = stop + 3;
        } else {
            start = start + 3;
        } 
    }
}

但我们还没有完成。如果我们以这种方式运行代码,那么事情将与您当前的代码完全相同。现在indexOf()函数的作用是返回字符串开头的索引。所以当你找到ATG的索引时,它会返回零。好吧,你想要的字符串从索引3开始,因为atg是三个字符长。通过在结果中添加三个可以轻松解决这个问题。您需要每次都这样做,而不仅仅是在if语句失败时。如果这应该输出多个基因,你可能会尝试重构你的代码,最好远离无限循环。主要问题是在if语句中,您正在检查我们是否在字符串的末尾,然后将start设置为stop + 3。但是循环再次运行并再次设置为atg索引。这是一种无可否认地抛弃loc变量的症状。

public static void printAll(String dna) {
    String dnaLow = dna.toLowerCase();
    int start = 0;
    int stop = 0;
    start = dnaLow.indexOf( "atg", start ) + 3;
    while (start < dna.length())
    {
        stop = findStopIndex( dnaLow, start );
        System.out.println( dna.substring(start, stop) );
        start = stop + 3;
    }   
}

我还在循环外部初始化了stop变量,但这是个人偏好,并不重要。

编辑: 在处理多个项目时,For循环是你的朋友。这在findStopIndex()函数中很明显。使用for循环实际上更容易编写此函数。我们要做的是创建数组来保存我们的密码子和索引,这样每个密码子就有一个索引。然后我们迭代它们尝试为每个找到一个停止索引。如果我们找不到,那么我们将相应的索引设置为字符串的结尾。

public static int findStopIndex(String dna, int index){
    String endCodons[] = { "tga", "taa", "tag"};
    int stopIndexes[] = new int[3];
    for(int i = 0; i<3 ;i++)  
    {
        stopIndexes[i] = dna.indexOf(endCodons[i], index);
        if(stopIndexes[i]==-1||(stopIndexes[i] - index) % 3 != 0)
            stopIndexes[i] = dna.length();
    }
    return Math.min(stopIndexes[0], Math.min(stopIndexes[1],stopIndexes[2]));
}