CodeWars ComplementaryDNA

samuel Jo·2023년 6월 7일
0

codewars

목록 보기
20/46

Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms.

If you want to know more: http://en.wikipedia.org/wiki/DNA

In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". Your function receives one side of the DNA (string, except for Haskell); you need to return the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell).

More similar exercise are found here: http://rosalind.info/problems/list-view/ (source)

Example: (input --> output)

"ATTGC" --> "TAACG"
"GTAT" --> "CATA"

A <=> T
G <=> C
이런식으로 바뀐다고 보면된다.

첫번째 for문과 switch문으로 짠 코드

/**for문과 switch문 */
function DNAStrand(dna) {
    //your code here
    // 1. T > A 
    //    A < T
    //    G > C
    //    C > G
    let empty = "";

    for (let i = 0; i < dna.length; i++) {
        const char = dna[i];
        switch (char) {
            case "A":
                empty += "T";
                break;
            case "T":
                empty += "A";
                break;
            case "C":
                empty += "G";
                break;
            case "G":
                empty += "C";
                break;
        }
    }
    return empty;
}

사실 처음에 생각한 코드는 string을 스프레드 문법으로 배열로 바꿔주고 다시 join()으로 string으로 바꿔주는걸 생각했다.

객체리터럴을 만들어 A는 T, T는 A, C는 G ,G는 C
map으로 순회하는동안 맞는 문자를 찾아 배열에 추가해줌.

function getComplementaryDNA(dna) {
  const complementaryMap = {
    A: "T",
    T: "A",
    C: "G",
    G: "C",
  };

  const complementary = [...dna].map((nucleotide) => complementaryMap[nucleotide]);

  return complementary.join("");
}

profile
step by step

0개의 댓글