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
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;
}