프로그래머스 코딩테스트_3

cho·2023년 12월 16일

📕Question

정수 num1과 num2가 매개변수로 주어질 때, num1을 num2로 나눈 값에 1,000을 곱한 후 정수 부분을 return 하도록 soltuion 함수를 완성해주세요.

입출력 예

num1num2result
321500
732333
11662

✏️Answer

const solution = (num1, num2) => Math.floor(num1 / num2 * 1000)
const solution = (num1, num2) => Math.trunc(num1 / num2 * 1000)

🌟Math.floor()

The Math.floor() static method always rounds down and returns the largest integer less than or equal to a given number.
주어진 숫자와 같거나 작은 정수 중에서 가장 큰 수를 반환한다.

console.log(Math.floor(5.95));
// Expected output: 5

console.log(Math.floor(5.05));
// Expected output: 5

console.log(Math.floor(5));
// Expected output: 5

console.log(Math.floor(-5.05));
// Expected output: -6

🌟Math.trunc()

The Math.trunc() static method returns the integer part of a number by removing any fractional digits.
주어진 값의 소수부분을 제거하고 숫자의 정수부분을 반환한다.

console.log(Math.trunc(13.37));
// Expected output: 13

console.log(Math.trunc(42.84));
// Expected output: 42

console.log(Math.trunc(0.123));
// Expected output: 0

console.log(Math.trunc(-0.123));
// Expected output: -0

📕Question

정수 배열 numbers가 매개변수로 주어집니다. numbers의 각 원소에 두배한 원소를 가진 배열을 return하도록 solution 함수를 완성해주세요.

입출력 예

numbersresult
[1, 2, 3, 4, 5][2, 4, 6, 8, 10]
[1, 2, 100, -99, 1, 2, 3][2, 4, 200, -198, 2, 4, 6]

✏️Answer

//내 답
function solution(numbers) {
    var answer = [];
    for(let i = 0; i < numbers.length ; i++){
        answer.push(numbers[i] * 2);
    }
    return answer;
}

🌟push()

The push() method of Array instances adds the specified elements to the end of an array and returns the new length of the array.
push() 메서드는 배열의 끝에 하나 이상의 요소를 추가하고 배열의 새로운 길이를 반환한다.

const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// Expected output: 4
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

✏️Answer

function solution(numbers) {
    return numbers.reduce((a, b) => [...a, b * 2], []);
}

🌟reduce()

The reduce() method of Array instances executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element.

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue,
);

console.log(sumWithInitial);
// Expected output: 10

✏️Answer

const solution = (numbers) => numbers.map((number) => number * 2)

🌟map()

📕Question

중앙값은 어떤 주어진 값들을 크기의 순서대로 정렬했을 때 가장 중앙에 위치하는 값을 의미합니다. 예를 들어 1, 2, 7, 10, 11의 중앙값은 7입니다. 정수 배열 array가 매개변수로 주어질 때, 중앙값을 return 하도록 solution 함수를 완성해보세요.

입출력 예

arrayresult
[1, 2, 7, 10, 11]7
[9, -1, 0]0

✏️Answer

function solution(array) {
      // 배열을 오름차순으로 정렬
    array.sort(function (a, b) {
        return a - b;
    });
  
      // 배열의 중앙 인덱스 계산
    var midIndex = Math.floor(array.length / 2);
  
        // 중앙값 반환
    return array[midIndex];
}

🌟array.sort()

sort() 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다. 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다. 정렬 속도와 복잡도는 각 구현방식에 따라 다를 수 있습니다.
복사본이 만들어지는 것이 아니라 원래의 배열이 정렬되는 것이니 주의해야한다.

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// Expected output: Array [1, 100000, 21, 30, 4]

compareFunction이 제공되지 않으면 요소를 문자열로 변환하고 유니 코드 코드 포인트 순서로 문자열을 비교하여 정렬됩니다. 예를 들어 "바나나"는 "체리"앞에옵니다. 숫자 정렬에서는 9가 80보다 앞에 오지만 숫자는 문자열로 변환되기 때문에 "80"은 유니 코드 순서에서 "9"앞에옵니다.

참조:
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

📕Question

최빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다. 정수 배열 array가 매개변수로 주어질 때, 최빈값을 return 하도록 solution 함수를 완성해보세요. 최빈값이 여러 개면 -1을 return 합니다.

입출력 예

arrayresult
[1, 2, 3, 3, 3, 4]3
[1, 1, 2, 2]-1
[1]1

✏️Answer

function solution(array) {
    var frequency = {};

    // 배열 내의 각 원소의 빈도를 계산
    array.forEach(num => frequency[num] = (frequency[num] || 0) + 1);

    var mode = -1;
    var maxFrequency = 0;

    // 최빈값 찾기
    for (var key in frequency) {
        if (frequency[key] > maxFrequency) {
            mode = parseInt(key);
            maxFrequency = frequency[key];
        } else if (frequency[key] === maxFrequency) {
            mode = -1;
        }
    }

    return mode;
}

🌟array.forEach()

Array. 인스턴스의 forEach() 메서드는 각 배열 요소에 대해 제공된 함수를 한 번씩 실행합니다.

const array1 = ['a', 'b', 'c'];

array1.forEach((element) => console.log(element));

// Expected output: "a"
// Expected output: "b"
// Expected output: "c"

✏️Answer2

function solution(array) {
    // 빈도를 저장할 Map 객체 생성
    let m = new Map();

    // 배열을 순회하며 각 원소의 빈도를 Map에 저장
    for (let n of array) {
        m.set(n, (m.get(n) || 0) + 1);
    }

    // Map을 배열로 전환하고 빈도를 기준으로 내림차순 정렬
    m = [...m].sort((a, b) => b[1] - a[1]);

    // 최빈값 반환
    return m.length === 1 || m[0][1] > m[1][1] ? m[0][0] : -1;
}

🌟array.map()

map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

const array1 = [1, 4, 9, 16];

// Pass a function to map
const map1 = array1.map((x) => x * 2);

console.log(map1);
// Expected output: Array [2, 8, 18, 32]

0개의 댓글