본문 바로가기

코딩 테스트/Codility

Codility FrogRiverOne JavaScript 풀이

https://app.codility.com/programmers/lessons/4-counting_elements/frog_river_one/

 

FrogRiverOne coding task - Learn to Code - Codility

Find the earliest time when a frog can jump to the other side of a river.

app.codility.com

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

function solution(X, A) {
    // write your code in JavaScript (Node.js 8.9.4)
    return A.indexOf(X);
}

이는 문제는 잘못 이해하고 제출한 코드이다.

예를 들어, X가 5로, A를 [1,2,3,5,4,5]라고 가정하면

문제를 처음 이해했을 때는 3이라고 출력하면 되는 줄 알았는데,

배열 값 중 5를 찾기 전에 1, 2, 3, 4 가 한 번씩 나와야 하므로 답은 5가 된다.

그럼에도 불구하고 스코어는 69인가 기록했던 거 같다.

 

두 번째로 제출한 코드는 아래와 같다.

function solution(X, A) {
    // write your code in JavaScript (Node.js 8.9.4)
    let arr = [];
    let result;
    
    for(let i = 0 ; i < X ; i++) {
        arr.push(A.indexOf(i));
    }
    
    return (Math.max.apply(arr) > A.indexOf(X)) ? A.indexOf(X, Math.max.apply(arr)) : A.indexOf(X);
}

이 코드는 문제를 다시 이해하고 작성한 코드이지만 스코어는 오히려 19인가 기록했다.

정확성은 물론이고, 성능 문제도 있다.

 

다른 분들이 해결한 사례를 찾아보니 나와 다른 로직이지만,

https://github.com/daraosn/codility/blob/master/02-CountingElements/01-FrogRiverOne/javascript/solution.js

 

daraosn/codility

Solutions for Codility.com problems. Contribute to daraosn/codility development by creating an account on GitHub.

github.com

function solution(X, A) {
    var sum = 0;
    var expected = (X * (X + 1)) / 2;
    var positions = [];
    for (var i in A) {
        var current = A[i];
        if(!positions[current]) {
            positions[current] = true;
            sum += current;
            if (sum == expected) {
                return +i;
            }
        }
    }
    return -1;
}

이런 코드를 발견했다.