💡 두 배열이 얼마나 유사한지 확인해보려고 합니다. 문자열 배열 s1
과 s2
가 주어질 때 같은 원소의 개수를 return하도록 solution 함수를 완성해주세요.
문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/120903
function solution(s1, s2) {
const S1 = new Set(s1);
const S2 = new Set(s2);
// 같은 원소의 개수를 세기 위한 변수를 초기화
let count = 0;
// s1의 고유한 원소를 순회하면서 s2에 있는지 확인하고 같은 원소의 개수를 증가시킴
S1.forEach(element => {
if (S2.has(element)) {
count++;
}
});
return count;
}
💡 등차수열 혹은 등비수열 common
이 매개변수로 주어질 때, 마지막 원소 다음으로 올 숫자를 return하도록 solution 함수를 완성해보세요.
문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/120924
function solution(common) {
if (common[2] - common[1] === common[1] - common[0]) {
return common.pop() + common[1] - common[0];
} else {
return common.pop() * (common[1] / common[0]);
}
}
💡 정수 n
을 기준으로 n
과 가까운 수부터 정렬하려고 합니다. 이때 n
으로부터의 거리가 같다면 더 큰 수를 앞에 오도록 배치합니다. 정수가 담긴 배열 numlist
와 정수 n
주어질 때 numlist
의 원소를 n
으로부터 가까운 순서대로 정렬한 배열을 return하도록 solution 함수를 완성해주세요.
문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/120880
function solution(numlist, n) {
// numlist를 정렬합니다. 정렬 순서는 거리와 값에 따라 결정됩니다.
numlist.sort((a, b) => {
// 거리가 같으면 값이 큰 순서로 정렬합니다.
const distA = Math.abs(a - n);
const distB = Math.abs(b - n);
if (distA === distB) {
return b - a;
} else {
return distA - distB;
}
});
return numlist;
}