HR - Sales by Match
문제
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;
}
Author And Source
이 문제에 관하여(HR - Sales by Match), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@goody/HR-Sales-by-Match저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)