JS 알고리즘 1주차 React

박규원·2023년 9월 25일
0

JS 알고리즘

목록 보기
9/11

배열의 유사도.

두 배열이 얼마나 유사한지 확인해보려고 합니다. 문자열 배열 s1과 s2가 주어질 때 같은 원소의 개수를 return하도록 solution 함수를 완성해주세요.

제한사항
1 ≤ s1, s2의 길이 ≤ 100
1 ≤ s1, s2의 원소의 길이 ≤ 10
s1과 s2의 원소는 알파벳 소문자로만 이루어져 있습니다
s1과 s2는 각각 중복된 원소를 갖지 않습니다.

function solution(s1, s2) {
    var answer = 0;
    
        answer=s1.filter(x=>s2.includes(x));
        answer=answer.length
    
    return answer;
    
}

다음에 올 숫자

문제 설명
등차수열 혹은 등비수열 common이 매개변수로 주어질 때, 마지막 원소 다음으로 올 숫자를 return 하도록 solution 함수를 완성해보세요.

제한사항
2 < common의 길이 < 1,000
-1,000 < common의 원소 < 2,000
common의 원소는 모두 정수입니다.
등차수열 혹은 등비수열이 아닌 경우는 없습니다.
등비수열인 경우 공비는 0이 아닌 정수입니다.
입출력 예
common result
[1, 2, 3, 4] 5
[2, 4, 8] 16

function solution(common) {
    var answer = 0;
    
    var leng=common.length;
    
    if(common[1]*2==common[0]+common[2])
        answer=common[leng-1]*2 - common[leng-2];
    
    else if(Math.pow(common[1],2)==common[0]*common[2])
        answer=Math.pow(common[leng-1],2)/common[leng-2];
    
    return answer;
}

특이한 정렬
문제 설명
정수 n을 기준으로 n과 가까운 수부터 정렬하려고 합니다. 이때 n으로부터의 거리가 같다면 더 큰 수를 앞에 오도록 배치합니다. 정수가 담긴 배열 numlist와 정수 n이 주어질 때 numlist의 원소를 n으로부터 가까운 순서대로 정렬한 배열을 return하도록 solution 함수를 완성해주세요.

제한사항
1 ≤ n ≤ 10,000
1 ≤ numlist의 원소 ≤ 10,000
1 ≤ numlist의 길이 ≤ 100
numlist는 중복된 원소를 갖지 않습니다.
입출력 예
numlist n result
[1, 2, 3, 4, 5, 6] 4 [4, 5, 3, 6, 2, 1][10000,20,36,47,40,6,10,7000] 30 [36, 40, 20, 47, 10, 6, 7000, 10000]
입출력 예 설명
입출력 예 #1

4에서 가까운 순으로 [4, 5, 3, 6, 2, 1]을 return합니다.
3과 5는 거리가 같으므로 더 큰 5가 앞에 와야 합니다.
2와 6은 거리가 같으므로 더 큰 6이 앞에 와야 합니다.
입출력 예 #2

30에서 가까운 순으로 [36, 40, 20, 47, 10, 6, 7000, 10000]을 return합니다.
20과 40은 거리가 같으므로 더 큰 40이 앞에 와야 합니다.

// function solution(numlist, n) {
//     var answer = [];
//     var copy = new Array(numlist.length);
    
//     for (var i=0;i<numlist.length;i++){
//         if((numlist[i]-n)<0)
//             copy[i]= (-1*(numlist[i]-n));
//         else
//             copy[i]=(numlist[i]-n);
//     }
    
//     copy.sort();
    
//     for (var i=0;i<copy.length;i++){
//         if(i==0)
//             answer[i]=copy[i]+n;
        
//         else if(copy[i]==copy[i-1])
//             answer[i]=(n-copy[i]);
//         else
//             answer[i]=(copy[i]+n);
//     }
    
//     return answer;
// }


function solution(numlist, n) {
    // Custom sorting function
    function customSort(a, b) {
        const diffA = Math.abs(a - n);
        const diffB = Math.abs(b - n);

        if (diffA === diffB) {
            return b - a; // If the distances are the same, sort by larger value first
        }

        return diffA - diffB; // Sort by absolute difference to n
    }

    // Sort numlist using the custom sorting function
    numlist.sort(customSort);

    return numlist;
}


profile
Just do IT

0개의 댓글