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 and one of color . There are three odd socks left, one of each color. The number of pairs is.
Function Description
Complete the sockMerchant function in the editor below.
sockMerchant has the following parameter(s):
- int n: the number of socks in the pile
- int ar[n]: the colors of each sock
Returns
- int: the number of pairs
Input Format
The first line contains an integer n, the number of socks represented in ar.
The second line contains n space-separated integers, ar[i], the colors of the socks in the pile.
function sockMerchant(n, ar) {
// Write your code here
const uniqueValues = [... new Set(ar)]
let count = 0
uniqueValues.forEach(value => {
const filterValues = ar.filter(element => element == value)
const pairsNumber = Math.floor(filterValues.length/2)
count += pairsNumber
})
return count
}
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.