In this Sales by Match HackerRank Problem, 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 sock
Returns
- int: the number of pairs
Input Format
The first line contains an integer , the number of socks represented in .
The second line contains space-separated integers, , the colors of the socks in the pile.
Constraints
- where
Sample Input
STDIN Function
----- --------
9 n = 9
10 20 20 10 10 30 50 10 20 ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]
Sample Output
3
Explanation
There are three pairs of socks.
Sales by Match HackerRank Problem Solutions
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in JavaScript
function sockMerchant(n, ar) {
let equal = 0;
const variants = new Set(ar);
let pairCount = [];
variants.forEach((value)=>{
for(let i=0; i<ar.length;i++){
if(value == ar[i]){
equal +=1;
}
}
pairCount.push(equal);
equal = 0;
})
pairCount = pairCount.map((item) => Math.floor(item/2));
pairCount = pairCount.reduce((acc, val) => acc+val,0);
return pairCount;
}
Sales by Match Problem Solution in Python
def sockMerchant(n, ar):
color_dict = dict()
# Count the number of socks for each color
for i in range(len(ar)):
if ar[i] in color_dict:
color_dict[ar[i]] +=1
else:
color_dict[ar[i]] = 1
# Find the total number of pairs
nb_pairs = 0
for value in color_dict.values():
nb_pairs += int(value/2)
return nb_pairs
Problem Solution in Java
public static int sockMerchant(int n, List ar) {
Collections.sort(ar);
int counter = 0;
for (int i = ar.size() - 1; i >=1; i--) {
if (ar.get(i).equals( ar.get(i - 1))){
counter++;
i = i -1;
}
}
return counter;
}
Solve original Problem on HackerRank here. Checkout more HackerRank Problems