0
ArrayList<String> dnaArray = new ArrayList<>();
ArrayList<Character> compArray = new ArrayList<Character>();

// [tac, tat, tta, aaa, aac, aca, aac, ttt]

public void createCompliment() {
    for (String letters : dnaArray) {
        for (int i = 0, len = letters.length(); i < len; i++) {
            char character = letters.charAt(i);
            if (character == 'a'){
                character = 't';
            } else if (character == 'c') {
                character = 'g';
            }
            compArray.add(character);
        }
    }
}

How would I access specific characters, change 'a' to 't' and similarily from 'c' to 'g'. Then added to a new arraylist and return something like:

[ttg, ttt, ttt, ttt, ttg, tgt, ttg, ttt]

instead of: [t, t, g, t, t, t, t, t, t, t, t, t, t, t, g, t, g, t, t, t, g, t, t, t]

appreciate it

1
  • collect into another list and wrap it up once it hits the desired size, add it to the outer list then. so some kind of inner.add(foo) and then if (inner.size() > desired) you do outer.add(inner) and inner = new ArrayList<>() as preparation for the next batch. Commented Aug 14, 2020 at 9:37

2 Answers 2

1

the easiest way in my opinion is to use string replace:

ArrayList<String> dnaArray = new ArrayList<>();
ArrayList<String> compArray = new ArrayList<String>();

public void createCompliment() {
    for (String letters : dnaArray) {
        compArray.add(letters.replace('a', 't').replace('c', 'g'));
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This would work well but will Java optimise it to do it in one traverse.
@AbhishekChauhan you're right, this does 2 traverses. With the given inputs I don't think complexity is an issue.
1

You can use a StringBuilder() to create the new String then add it to compArray.

Try this:

for(String letters : dnaArray) {
    StringBuilder sb = new StringBuilder();
    for(int i=0; i<letters.length(); i++) {
        char character = letters.charAt(i);
        if (character == 'a'){
            sb.append("t");
        }
        else if (character == 'c'){
            sb.append("g");
        } else {
            sb.append(String.valueOf(character));
        }
    }
    compArray.add(sb.toString());
}

Output:

[ttg, ttt, ttt, ttt, ttg, tgt, ttg, ttt]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.