Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashMap;
- public class Main {
- public static void main(String[] args) {
- HashMap<String, Integer> codons = codons("atatcgcata");
- System.out.println(codons);
- }
- // Create the static method that returns a HashMap with a String as the key and an Integer as the value.
- // The parameter nucleotides is a string that we need to find the frequency of.
- public static HashMap<String, Integer> codons(String nucleotides) {
- // We need to create the HashMap to store the frequencies in.
- HashMap<String, Integer> frequency = new HashMap<>();
- // Create the for loop that starts at the beginning o the nucleotides string and ends two characters before the
- // end of it. This is so we don't get an out of bounds substring.
- for (int index = 0; index < nucleotides.length() - 2; index++) {
- // Create the key to search for in the frequency HashMap.
- // Get the three characters starting from index ending at index + 3.
- /*
- *(Assume nucleotides is atatcgcata)*
- How does this work? Well, at the start of the for loop index is 0, the beginning of the string.
- So, first iteration index = 0
- substring(0, 0 + 3) -> substring(0, 3)
- is going to be ata
- Second iteration index = 1
- substring(1, 1 + 3) -> substring(1, 4)
- is going to be tat (note the index now starts at 1, so the substring is offset by 1 character)
- Third iteration index = 2
- substring(2, 2 + 3) -> substring(2, 5)
- is going to be atc (note the index now starts at 2, so the substring is offset by 2 characters)
- fourth iteration index = 3
- substring(3, 3 + 3) -> substring(3, 6)
- is going to be tcg (note the index now starts at 3, so the substring is offset by 3 characters)
- fifth iteration index = 4
- substring(4, 4 + 3) -> substring(4, 7)
- is going to be cgc (note the index now starts at 4, so the substring is offset by 3 characters)
- ... and so on. See if you can finish the for loop.
- */
- String key = nucleotides.substring(index, index + 3);
- // Now to record how many times it shows up. First we need to check if the key already exists in the
- // frequency table. If it does exist (aka if it does not equal null (!= null)) then we add one to the
- // frequency since it has already showed up.
- if (frequency.get(key) != null) {
- frequency.put(key, frequency.get(key) + 1);
- } else {
- // In this case, the key does not exist so we need to add it to the frequency HashMap,
- // that means he need to set the key in the HashMap to 1 since it shows up at least once.
- frequency.put(key, 1);
- }
- }
- return frequency;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement