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"]].
function pairElement(str) {let res = []for (let char of str) {console.log(char)switch (char) {case "A":res.push(["A", "T"])break;case "T":res.push(["T", "A"])break;case "C":res.push(["C", "G"])break;case "G":res.push(["G", "C"])break;}}return res;}console.log(pairElement("GCG"))
答案
使用split
"GCG".split()//["GCG"]"GCG".split('')//(3) ["G", "C", "G"]
使用map
function pairElement(str) {//create object for pair lookupvar pairs = {A: "T",T: "A",C: "G",G: "C"};//split string into array of charactersvar arr = str.split("");//map character to array of character and matching pairreturn arr.map(x => [x, pairs[x]]);}//test herepairElement("GCG");
Code Explanation
- First define an object with all pair possibilities, this allows us to easily find by key or value.
- Split
strinto 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.
