DNA Pairing

The DNA strand is missing the pairing element. Take each character, get its pair, and return the results as a 2d array.

Base pairs are a pair of AT and CG. Match the missing element to the provided character.

Return the provided character as the first element in each array.

For example, for the input GCG, return [["G", "C"], ["C","G"], ["G", "C"]]

The character and its pair are paired up in an array, and all the arrays are grouped into one encapsulating array.

pairElement("ATCGA") should return [["A","T"],["T","A"],["C","G"],["G","C"],["A","T"]].

Passed

pairElement("TTGAG") should return [["T","A"],["T","A"],["G","C"],["A","T"],["G","C"]].

Passed

pairElement("CTCTA") should return [["C","G"],["T","A"],["C","G"],["T","A"],["A","T"]].

  1. function pairElement(str) {
  2. let res = []
  3. for (let char of str) {
  4. console.log(char)
  5. switch (char) {
  6. case "A":
  7. res.push(["A", "T"])
  8. break;
  9. case "T":
  10. res.push(["T", "A"])
  11. break;
  12. case "C":
  13. res.push(["C", "G"])
  14. break;
  15. case "G":
  16. res.push(["G", "C"])
  17. break;
  18. }
  19. }
  20. return res;
  21. }
  22. console.log(
  23. pairElement("GCG")
  24. )

答案

使用split

https://forum.freecodecamp.org/t/javascript-string-prototype-split-split-explained-with-examples/15944

  1. "GCG".split()
  2. //["GCG"]
  3. "GCG".split('')
  4. //(3) ["G", "C", "G"]

使用map

  1. function pairElement(str) {
  2. //create object for pair lookup
  3. var pairs = {
  4. A: "T",
  5. T: "A",
  6. C: "G",
  7. G: "C"
  8. };
  9. //split string into array of characters
  10. var arr = str.split("");
  11. //map character to array of character and matching pair
  12. return arr.map(x => [x, pairs[x]]);
  13. }
  14. //test here
  15. pairElement("GCG");

Code Explanation

  • First define an object with all pair possibilities, this allows us to easily find by key or value.
  • Split str into a characters array so we can use each letter to find its pair.
  • Use the map function to map each character in the array to an array with the character and its matching pair, creating a 2D array.