Skip to content

Instantly share code, notes, and snippets.

@Rdilorenzo73
Last active November 4, 2018 19:18
Show Gist options
  • Save Rdilorenzo73/e9253b3a0598959a3744ef75506ca4a8 to your computer and use it in GitHub Desktop.
Save Rdilorenzo73/e9253b3a0598959a3744ef75506ca4a8 to your computer and use it in GitHub Desktop.
Java Data Structure - nucleotide count

A Java exercise taken from Exercism.io

I did not create this assignment. The coded solution is mine. This was a Java practice project which helped me with String manipulation methods and data structures.


Given a single stranded DNA string, compute how many times each nucleotide occurs in the string.

The genetic language of every living thing on the planet is DNA. DNA is a large molecule that is built from an extremely long sequence of individual elements called nucleotides. 4 types exist in DNA and these differ only slightly and can be represented as the following symbols: 'A' for adenine, 'C' for cytosine, 'G' for guanine, and 'T' thymine.

Given: A DNA string

Return: Four integers (separated by spaces) counting the respective number of times that the symbols 'A', 'C', 'G', and 'T' occur in s.

AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC -> 20 12 17 21
import java.util.LinkedHashMap;
import java.util.Map;
/*
java solution to http://rosalind.info/problems/dna/
*/
public class DNA {
private String theDNA;
public DNA(String string) {
theDNA = string;
}
public int count(char c) {
int theCount = 0;
//copy of original DNA sequence
String dnaCopy = new String(theDNA);
//letters in a DNA strand
String theLetters = "ACGT";
//as long as the letter is still in the strand copy
while(dnaCopy.indexOf(c) != -1)
{
//find the position
int thePosition = dnaCopy.indexOf(c);
//remove the letter
String before = dnaCopy.substring(0,thePosition);
String after = dnaCopy.substring(thePosition+1);
//make a new copy of the DNA strand minus the letter
dnaCopy= before+after;
//increase the count
theCount++;
}
return theCount;
}
public Map<Character, Integer> nucleotideCounts() {
Map<Character, Integer> theResults = new LinkedHashMap<Character, Integer>();
theResults.put('A', this.count('A'));
theResults.put('C', this.count('C'));
theResults.put('G', this.count('G'));
theResults.put('T', this.count('T'));
return theResults;
}
public static void main(String[] args) {
DNA test = new DNA("AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC");
for (Character ltr: test.nucleotideCounts().keySet()){
String value = test.nucleotideCounts().get(ltr).toString();
System.out.print(value + " ");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment