lots of exercises in java... from https://github.com/exercism/java

example.java 1.0KB

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