简体   繁体   中英

Best practice with multiple for loop iterators

I'm trying to alter and reverse an array. As such, I want loop with a negative iterator (to access the initial array values) and a positive iterator (to write to the new array). Here's the code I have at this point. (For those who know some biology, this code writes the reverse complement of a DNA string.)

final char[] DNA = {'G','A','T','T','A','C','A'};
char[] revComp = new char[DNA.length];

int j = 0;
for (int i = DNA.length - 1; i >= 0; i--) {
   switch (DNA[i]) {
      case 'A': DNA[i] = 'T'; break;
      case 'T': DNA[i] = 'A'; break;
      case 'C': DNA[i] = 'G'; break;
      case 'G': DNA[i] = 'C'; break;
   }
   revComp[j] = DNA[i];
   j++;
}

As you'll notice, I have a normal i iterator and an extra j iterator that I just didn't know where to put. Is this the best way to approach this sort of situation (where two iterators are needed), or would it be better if I did it a bit differently?

You could eliminate your "second" iterator (by which I mean loop counter) like

for (int i = 0; i < DNA.length; i++) {
    switch (DNA[i]) {
    case 'A':
        DNA[i] = 'T';
        break;
    case 'T':
        DNA[i] = 'A';
        break;
    case 'C':
        DNA[i] = 'G';
        break;
    case 'G':
        DNA[i] = 'C';
        break;
    }
    revComp[i] = DNA[DNA.length - i - 1];
}

Or like

for (int i = DNA.length - 1; i >= 0; i--) {
    switch (DNA[i]) {
    case 'A':
        DNA[i] = 'T';
        break;
    case 'T':
        DNA[i] = 'A';
        break;
    case 'C':
        DNA[i] = 'G';
        break;
    case 'G':
        DNA[i] = 'C';
        break;
    }
    revComp[DNA.length - i - 1] = DNA[i];
}

which both produce a DNA of

[C, T, A, A, T, G, T]

and a revComp

[T, G, T, A, A, T, C]

when I checked with

System.out.println("revComp: " + Arrays.toString(revComp));
System.out.println("DNA: " + Arrays.toString(DNA));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM