Skip to content

Commit e151adb

Browse files
committed
java: Add sample nucleotide-count implementation
1 parent a331a34 commit e151adb

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
public final class DNA {
5+
private final String sequence;
6+
7+
public DNA(String sequence) {
8+
this.sequence = sequence;
9+
}
10+
11+
public int count(char base) {
12+
if (isCountable(base))
13+
throw new IllegalArgumentException(base + " is not a nucleotide");
14+
15+
try {
16+
return nucleotideCounts().get(base);
17+
} catch (NullPointerException e) {
18+
return 0;
19+
}
20+
}
21+
22+
private static boolean isCountable(char base) {
23+
final String COUNTABLE_NUCLEOTIDES = "ACGTU";
24+
return COUNTABLE_NUCLEOTIDES.indexOf(base) == -1;
25+
}
26+
27+
public Map<Character, Integer> nucleotideCounts() {
28+
Map<Character, Integer> counts = emptyCounts();
29+
for (char c : sequence.toCharArray()) {
30+
counts.put(c, counts.get(c) + 1);
31+
}
32+
return counts;
33+
}
34+
35+
private static Map<Character, Integer> emptyCounts() {
36+
Map<Character, Integer> counts = new HashMap<Character, Integer>();
37+
counts.put('A', 0);
38+
counts.put('C', 0);
39+
counts.put('T', 0);
40+
counts.put('G', 0);
41+
return counts;
42+
}
43+
}

0 commit comments

Comments
 (0)