HR - Sales by Match

Goody·2021년 3월 9일
0

알고리즘

목록 보기
62/122

문제

There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

Example
n = 7
ar = [1,2,1,2,1,3,2]

There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2.


예시

STDIN                       Function
-----                       --------
9                           n = 9
10 20 20 10 10 30 50 10 20  ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]

// 3


풀이

  • 주어진 배열을 순회하면서 원소를 키로 갖는 객체에 count를 집어넣는다.
  • 방금 만든 객체를 순환하면서 값이 1 보다 큰 경우, 값을 짝수로 맞추고 answer에 더한다.
  • answer 를 2로 나눈 뒤 반환한다.

코드

function sockMerchant(n, ar) {
    const nums = {};
    let answer = 0;

    ar.forEach((el, idx) => {
        if (!nums[el]) nums[el] = 1;
        else nums[el]++;
    });

    console.log(nums);
    const keys = Object.keys(nums);

    keys.forEach((el, idx) => {
        if (nums[el] > 1) {
            if(nums[el] % 2 !== 0 ) {
                nums[el]--;
            } 
            answer += nums[el];
        }
        
    })

    answer /= 2;
    return answer;
}

0개의 댓글