Quick and dirty, running on a loop, counting, gathering and calculating the socks ðŸ˜€

###### Exercise Description

John’s clothing store has a pile of n loose socks where each sock i is labeled with an integer, C(i), denoting its color. He wants to sell as many socks as possible, but his customers will only buy them in matching pairs. Two socks, i and j, are a single matching pair if C(i)=C(j).

Given n and the color of each sock, how many pairs of socks can John sell?

###### Solution

```
function getSocksPairs(socks) {
var counters = {};
var pairs = 0;
for (var i=0 ; i<socks.length ; i++) {
var cur = socks[i];
if (cur in counters) {
counters[cur]++;
} else {
counters[cur] = 1;
}
}
for (var counterKey in counters) {
pairs += Math.floor(counters[counterKey]/2);
}
return pairs;
}
```

## Leave a Reply