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
Unfortunately, I couldn't understand the logic of your proposed algorithm, But as an alternative solution, you may have a look at my code. Here is my javascript code for this problem which works fine.
First, I defined a dictionary (ar_count) and count each number from ar array and update the dictionary for the corresponding key. I defined the key in the form of "key"+ar[i] for easy coding and fast processing of finding the existing key and for counting pairs.
function sockMerchant(n, ar) {
var ar_count={};
for(let i=0; i<ar.length;i++){
if("key"+ar[i] in ar_count){
ar_count["key"+ar[i]]+=1;
}
else{
ar_count["key"+ar[i]]=1;
}
}
//console.log(ar_count);
var pairs=0;
for (var key in ar_count){
paires+=~~(ar_count[key]/2);
}
return pairs;
}