The problem I have to solve is this:
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
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 sockReturns
int: the number of pairs
My solution in javascript since I know very little of the language was this
function sockMerchant(n, ar) {
// Write your code here
let pairs=0;
let counter;
ar.sort()
for(let i=0; i < n; i++){
if (i == 0){
counter = 1;
}else{
if(ar[i] == ar[i-1]){
counter++;
}else{
pairs= pairs + Math.floor(counter/2);
counter= 1;
}
}
}
return pairs
}
The problem is that hackerranks complains because with this input
10
1 1 3 1 2 1 3 3 3 3
my output is 2 instead of 4. Can somebody tell me why because I can't see where the problem is. If someone can help me to see where is the issue, I will appreciate it Thanks in advance Jenifer