I realize there are many answers that simply solve how to do it in Java, but am looking for a solution that is conceptually similar to an implementation I might perform in a Python program, since that is far more familiar to me.
My Java function cgRatio
takes a DNA string and goes through every index to count the occurrence of "C" and "G" character values in the string and return the ratio relative to the length of the string. For example, if I pass the following string as the argument for the function:
"ATGGCGCATTAA"
I would get a return value of 5/12 or a float of 4.1666...
In Python, this function could be written as so:
def cgRatio(dna):
count = 0
for i in range(len(dna)):
if dna[i] == "C" or dna[i] == "G":
count += 1
return 1.0 * count/len(dna)
A simple print cgRatio("ATGGCGCATTAA")
will produce the desired result.
I've seen solutions such as taking dna.charAt(i)
and converting that back to a string or instantiating new char
objects at the start of the function for comparisons. This seems overly complicated for such a simple task. Is Python just superior in this task or is there a more efficient way to go about this in Java?
The simple java code would be:
for (int i = 0; i < dna.length(); i++) {
char c = dna.charAt(i);
if (c == 'C' || c == 'G') {
count++;
}
}
return (double)count / dna.length();
There is absolutely no reason to convert chars to "string" in order to compare them!
And in case you are looking for even "less" code solutions, you could be using "for each" style:
for (char c : dna.toCharArray()) {
Easy to understand, nice to read, but comes at the cost of creating a new char array.