본문 바로가기

코딩 테스트/Codility

Codility GenomicRangeQuery JavaScript 풀이

https://app.codility.com/programmers/lessons/5-prefix_sums/genomic_range_query/

 

GenomicRangeQuery coding task - Learn to Code - Codility

Find the minimal nucleotide from a range of sequence DNA.

app.codility.com

내가 처음에 제출한 코드는 아래와 같다.

function solution(S, P, Q) {
    // write your code in JavaScript (Node.js 8.9.4)
    let Sarr = S.split("");
    
    let dnaObj = {
        A : 1,
        C : 2,
        G : 3,
        T : 4
    }
    
    let resultArr = [];
    
    for (let i = 0 ; i < P.length ; i++) {
        if (P[i] === Q[i]) {
            resultArr.push(dnaObj[Sarr[P[i]]])
        } else {
            resultArr.push(dnaObj[Sarr.slice(P[i], Q[i]).sort()[0]]);
        }
    }
    
    return resultArr;
}

25 스코어를 기록했고, 정확성 테스트는 일부만 통과하고 성능 테스트는 모두 통과하지 못했다.

 

그래서, time complexity는 O(N + M), 100 스코어를 기록한 이 분의 코드를 참고했다.

https://github.com/yaseenshaik/codility-solutions-javascript/blob/master/GenomicRangeQuery.md

 

yaseenshaik/codility-solutions-javascript

Solutions for codility in javascript. Contribute to yaseenshaik/codility-solutions-javascript development by creating an account on GitHub.

github.com

function solution (S, P, Q) {
	var dna = '';
	var ans = [];

	for (var i=0; i < P.length; i++) {
		dna = S.slice(P[i], Q[i] + 1);

		if (dna.indexOf('A') !== -1) {
			ans.push(1)
		} else if (dna.indexOf('C') !== -1) {
			ans.push(2)
		} else if (dna.indexOf('G') !== -1) {
			ans.push(3)
		} else {
			ans.push(4)
		}
	}

	return ans;
}

 

신기한 것은 문자열로 주어지는 S에 slice 메소드는 쓸 수 있고, splice는 쓸 수 없다는 것이다.

MDN을 찾아보니 slice는 String.prototype과 Array.prototype에 모두 선언되어 있는 메소드이지만,

splice는 Array.prototype에만 선언되어 있는 메소드여서 쓸 수 있는 거 같다.

 

또한, if 문의 순서를 통해 필요한 로직을 짠 것도 간단하지만 좋은 소스라고 생각한다.