Reputation: 308
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?
Upvotes: 0
Views: 408
Reputation: 201477
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));
Upvotes: 2